Skip to content
This repository was archived by the owner on May 7, 2023. It is now read-only.

Files

Latest commit

 

History

History
26 lines (21 loc) · 608 Bytes

compose.md

File metadata and controls

26 lines (21 loc) · 608 Bytes
title type tags cover dateModified
Compose functions
snippet
function
tram-car-2
2020-11-02 19:27:07 +0200

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