foldr function in Python
ojeeves at gmail.com
Thu Nov 22 20:14:31 CET 2007
On Nov 22, 3:02 pm, Ant <ant... at gmail.com> wrote:
> Hi all,
> I've just been reading with interest this article:http://caos.di.uminho.pt/~ulisses/blog/2007/11/20/foldr-the-magic-fun...
> It's a useful function that (with a more intuitive name) could prove a
> compelling addition to the itertools module. In it's python form, it
> would be something like this:
> def reduce2 (fn, init, seq):
> return reduce(fn, seq, init)
> def foldr (function, initial):
> return partial(reduce2, function, initial)
> It's a bit different from the other itertools functions, in that
> rather than producing an iterator, it produces a function which
> reduces a iterator to a singe value.
> The advantages I see over reduce are that (a) it provides incentive to
> document the code and (b) it promotes reuse. For example:
> value = reduce(lambda x, y: "%s%s%s" % (x, "," if x else "", y),
> myList, "")
> commaSeparate = foldr(lambda x, y: "%s%s%s" % (x, "," if x else "",
> y), "")
> Of course the lambda function in this case could be a named function,
> helping with both readability and reuse, but I think the latter is
> conceptually easier to grasp when reading the code.
It's basically just one line to implement:
foldr = lambda f, i: lambda s: reduce(f, s, i)
It's just reduce with currying, I'm not sure it adds that much to what
python already offers.
More information about the Python-list