foldr function in Python
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Fri Nov 23 04:31:06 EST 2007
On Fri, 23 Nov 2007 00:50:30 -0800, Ant wrote:
> So my point really is that foldr (perhaps renamed to make_reducer or
> something) could create idioms that are more readable than using
> reduce directly.
The name is definitely not so good because there is a `foldr` in Haskell
that just works like `reduce()`. For partial applying you can use
``lambda`` or `functools.partial()`, unfortunately not with keyword
arguments as needed to set the initial value because `reduce()` just
accepts positional arguments. So let's define `foldr()` in terms of
`reduce()`::
foldr = lambda func, initial, iterable: reduce(func, iterable, initial)
comma_separate = partial(foldr, insert_comma, '')
`insert_comma()` is left as an exercise for the reader. :-)
I think that's better than a `make_reducer()`.
Of course it's a silly example because the "pythonic" way to define
`comma_separate()` is::
comma_separate = ','.join
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list