Medium: Interview Core · Problem 40 of 82

Compose Functions

MediumFunctionsPython

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?

  1. 7
  2. None
  3. 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.)