Chris Lamb


Mulletron was asking whether there was a higher-order function which computed the result of applying a given list of functions cummulatively from an initial value.

I claimed not, as 'reduce' was already the "list to single value" generalisation. As evidence, and to pass the time on my train journey, here is a version in Python:

def fnreduce(sequence, initial):
    return reduce(lambda x, y: lambda _: y(x(_)), \
        sequence, lambda _: _)(initial)

fn_list = [
    lambda a: a * 2,
    lambda a: a - 1,

assert fnreduce(fn_list, 2) == 3

Replacing y(x(_)) with x(y(_)) would apply the list in reverse order, and thus fail the assertion. I just hope you like lambydas.

Chris Lamb is a freelance software developer and the current Debian Project Leader. You can read other posts by me, see software I have written or read more about me. You can also follow me @lolamby.


Saturday 16th June 2007

Two comments