30秒学会 Python 片段 · 2023年5月8日

30秒学会 Python 片段 – Reverse compose functions

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

翻译自:https://www.30secondsofcode.org/python/s/compose-right