17

I want to get the result of a chain of computations from an initial value. I'm actually using the following code:

def function_composition(function_list, origin):
    destination = origin
    for func in function_list:
        destination = func(destination)
    return destination

With each function in function_list having a single argument.

I'd like to know if there is a similar function in python standard library or a better way (example: using lambdas) to do this.

4
  • 3
    This would be a fold of function application, in an FP style. E.g. in Haskell foldr ($) 7 [(+1), (^3), (*2)] evaluates to 2745. ($) is simply \f x -> f x. So reduce and lambda would be the python equivalent. Commented Jun 15, 2013 at 10:32
  • 3
    Your code is clear and concise - I would argue that there is no reason to try and compress it down. Commented Jun 15, 2013 at 10:33
  • @DonStewart: actually it's a fold of function composition. Commented Jun 15, 2013 at 11:46
  • @larsmans - depends on whether you want to fold composition and then apply, or just fold apply ... foldr ($) x [(+1),(^2)] vs foldr (.) id [(+1),(^2)] $ x. Commented Jun 15, 2013 at 14:09

1 Answer 1

20

Fold while calling.

destination = reduce((lambda x, y: y(x)), function_list, origin)
Sign up to request clarification or add additional context in comments.

5 Comments

Note that in 3.x, reduce is functools.reduce().
I needed to reverse variables in the lambda: destination = reduce((lambda x, y: y(x)), function_list, origin). Now it works.
Do you really believe this is a better way of doing this?
@larsmans I certainly find it easier to understand what this is doing and that it's correct.
It's a little more readable if you redefine the deprecated apply function: apply = lambda func, value: func(value); destination = reduce(apply, function_list, origin).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.