Files
30-seconds-of-code/snippets/compose_right.md
Isabelle Viktoria Maciohsek 19f636408c Make expertise a field
2022-03-01 20:27:27 +02:00

635 B

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

Performs left-to-right function composition.

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

def compose_right(*fns):
  return reduce(lambda f, g: lambda *args: g(f(*args)), fns)
add = lambda x, y: x + y
square = lambda x: x * x
add_and_square = compose_right(add, square)
add_and_square(1, 2) # 9