Skip to content

Latest commit

 

History

History
25 lines (20 loc) · 609 Bytes

compose-right.md

File metadata and controls

25 lines (20 loc) · 609 Bytes
title type language tags cover dateModified
Reverse compose functions
snippet
python
function
lavender-shelf
2020-11-02

Performs left-to-right function composition.

  • Use functools.reduce() to perform left-to-right function composition.
  • The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
from functools import reduce

def compose_right(*fns):
  return reduce(lambda f, g: lambda *args: g(f(*args)), fns)

add = lambda x, y: x + y
square = lambda x: x * x
add_and_square = compose_right(add, square)
add_and_square(1, 2) # 9