Reverse compose functions

OSCC · Python, Function · Nov 2, 2020

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

Recommended snippets

  • Compose functions

    Python, Function

    Performs right-to-left function composition.

  • Unfold list

    Python, Function

    Builds a list, using an iterator function and an initial seed value.

  • Check property

    Python, Function

    Creates a function that will invoke a predicate function for the specified property on a given dictionary.