Nicer way to write folding? (list reversal?)

andrew at acooke.org andrew at acooke.org
Thu Jan 3 02:37:45 EST 2002


[crossposting to comp.lang.functional in case someone there knows
whether there's a convention, but followup still to comp.lang.python]

Thanks, I didn't know that.  It seems to be

f(f(...f(f(c, xn), xn-1) ..., x2), x1)

rather than

f(x1, f(x2, ... f(xn-1, f(xn, c))...))

(ie the arguments to f are reversed).  Is there any consensus across
languages about which way round the arguments should be in foldr?

In ML, it's the second argument to the function that takes the output
of earlier results:

- foldr;
val it = fn : ('a * 'b -> 'b) -> 'b -> 'a list -> 'b


Cheers,
Andrew

In article <mailman.1010012464.8515.python-list at python.org> you wrote:
>> In the code below, foldr2 is clearly uglier than the rest.  Is there a
>> nicer way (without destructive reversal - yuck - of the list
>> argument)?  Also, are these things built-in (can't find them)?
> 
> foldr() is built-in.  It's called reduce().
> 
>  >>> from operator import add
>  >>> nums = [1, 2, 3, 4, 5]
>  >>> reduce(add, nums, 0)
>  15
> 
> ## Jason Orendorff    http://www.jorendorff.com/
> 

-- 
http://www.acooke.org



More information about the Python-list mailing list