Compose functions

Python, Function · Nov 2, 2020

Performs right-to-left function composition.

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

def compose(*fns):
  return reduce(lambda f, g: lambda *args: f(g(*args)), fns)
add5 = lambda x: x + 5
multiply = lambda x, y: x * y
multiply_and_add_5 = compose(add5, multiply)
multiply_and_add_5(5, 2) # 15

More like this

  • Reverse compose functions

    Performs left-to-right function composition.

    Python, Function · Nov 2, 2020

  • Unfold list

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

    Python, Function · Nov 2, 2020

  • Check property

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

    Python, Function · Nov 2, 2020