Files
30-seconds-of-code/snippets/compose.md
Angelos Chalaris 0f36c17995 Update explanations
Update explanation in digitize
Update explanation in delay
Update explanation in curry
Update explanation in compose_right
Update explanation in compose
2020-01-03 13:08:00 +02:00

559 B

title, tags
title tags
compose function,intermediate

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