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.

Comments (2)



June 19, 2007, 1:36 p.m. #

Here is the Haskell version of the function using foldl (I'd like to post in lupin's blog, but there is no way to put a comment there):

fnreduce' :: [(a->a)] -> a -> a
fnreduce' fs v = foldl (flip ($)) v fs

June 20, 2007, 2:16 a.m. #