Compose Functions
Write compose(*funcs) that returns a function applying all the given functions to its argument, from the last to the first, like in maths: compose(f, g, h)(x) is f(g(h(x))).
compose() with no functions returns a function that gives back its argument unchanged.
Understand the problem
Work out the order of application.
With f = lambda x: x + 1 and g = lambda x: x * 2, what is compose(f, g)(5)? (That is f(g(5)).)
The last function is applied first: g(5) = 10, then f(10) = 11. If you applied them left to right you would get g(f(5)) = 12: a different answer.
What should compose()(7) return?
7None- An error
No functions to apply means the identity: the argument comes back unchanged. This is the "empty case" of any chain: multiplying zero numbers gives 1, composing zero functions gives the identity.
Write the solution
Return the combined function.
def compose(*funcs):
# Write your code here.
pass
Hint 1: a question to ask yourself
In what order must you go through funcs, and what do you pass from one call to the next?
Hint 2: the shape of the answer
Return an inner function. Start with the argument, then loop over reversed(funcs), replacing the value by func(value) each time.
Reflect
Solution
def compose(*funcs):
def composed(value):
for func in reversed(funcs):
value = func(value)
return value
return composed
Another way: functools.reduce
from functools import reduce
def compose(*funcs):
return lambda value: reduce(lambda acc, func: func(acc), reversed(funcs), value)
What this tests: functions as values, *args, closures (the inner function remembers funcs), and reduce.
Order matters: mathematical composition applies the right-most function first. Many pipelines are easier to read left to right (a pipe function); the only difference is dropping reversed.
The empty case: a loop over no functions returns the value unchanged without any special code. When the base case falls out of the code naturally, you usually have the right design.
Cost: O(number of functions) per call.
What an interviewer might ask next: Write pipe(*funcs) that applies them left to right. (The same code without reversed.)
VISIBLE = 3
CASES = [
('f = lambda x: x + 1\ng = lambda x: x * 2\nresult = compose(f, g)(5)', 11, 'the last function runs first'),
('result = compose()(7)', 7, 'no functions: the identity'),
('result = compose(str.upper)("abc")', 'ABC', 'one function'),
('result = compose(len, str.split)("a b c")', 3, 'two functions with different types'),
('f = lambda x: x - 3\ng = lambda x: x * x\nh = lambda x: x + 1\nresult = compose(f, g, h)(2)', 6, 'three functions'),
('add = lambda x: x + 1\nresult = compose(add, add, add, add)(0)', 4, 'the same function four times'),
('c = compose(lambda x: x * 2)\nresult = (c(1), c(2), c(3))', (2, 4, 6), 'the composed function can be called many times'),
]