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.

Comments (2)

Odd_Bloke

lolololambda

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

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):

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

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