0 points

Python compose function - performs right-to-left function composition


Thu Jan 09 2020 19:00:00 GMT+0000 (UTC)

Posted by @peterents #python #function

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
content_copy Copy

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.