Files
30-seconds-of-code/snippets/compose.md
Isabelle Viktoria Maciohsek cbc78ee450 Bake dates into snippets
2021-06-13 19:38:10 +03:00

609 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
compose function,advanced 2020-01-02T15:51:20+02:00 2020-11-02T19:27:07+02:00

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