June 16th 2007

Fnreduce

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.




You can subscribe to new posts via email or RSS.