0 points

Performs right-to-left function composition.


dashboard

Mon Apr 20 2020 13:38:08 GMT+0000 (UTC)

Posted by @Cutesy #python #python #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

1.def compose(*fns):
  2.return reduce(lambda f, g: lambda *args: f(g(*args)), fns)
EXAMPLES
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
content_copy Copy

Function composition is a way of combining functions such that the result of each function is passed as the argument of the next function.

https://www.30secondsofcode.org/python/s/compose/