From 37f433feb7e7ce378980e9c3489c8da88128f5a2 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Thu, 2 Jan 2020 15:51:26 +0200 Subject: [PATCH] Add compose right --- snippets/compose_right.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 snippets/compose_right.md diff --git a/snippets/compose_right.md b/snippets/compose_right.md new file mode 100644 index 000000000..696f89da6 --- /dev/null +++ b/snippets/compose_right.md @@ -0,0 +1,24 @@ +--- +title: compose_right +tags: function,intermediate +--- + +Performs left-to-right function composition. + +Use `reduce()` to perform left-to-right function composition. +The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. + +```py +from functools import reduce + +def compose_right(*fns): + return reduce(lambda f, g: lambda *args: g(f(*args)), fns) +``` + +```py +add = lambda x, y: x + y +square = lambda x: x * x +add_and_square = compose_right(add,square) + +add_and_square(1, 2) # 9 +```