[Tutor] is "fold" same as "reduce"?
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Mon, 21 Jan 2002 22:10:33 -0800 (PST)
On Tue, 22 Jan 2002, Karthik Gurumurthy wrote:
> I got introduced to functional programming through python and i like
> it now..it was'nt the case a couple of months back though. a "lambda"
> used to put me off.
> I was doing some reading and i was just wondering if the "fold"
> construct is same as "reduce" in python?
Yes: Python's 'reduce' is a similar concept to 'fold' in a functional
language. For example, here's a function that uses reduce to reverse a
list:
###
def reverse(l):
return reduce(lambda x, y: [y] + x, [[]] + l)
###
Let's see if it works:
###
>>> reverse([1, 2, 3, 4])
[4, 3, 2, 1]
>>> reverse(['larry', 'curly' 'moe'])
['curlymoe', 'larry']
###
reduce() is a surprisingly versatile function; it can be applied to things
that can raise eyebrows. Here's another application to do filtering:
###
def filter(test_f, l):
def func(x, y):
if test_f(y):
return x + [y]
return x
return reduce(func, [[]] + l)
###
Does this work?
###
>>> filter(isEven, [3, 1, 4, 1, 5, 9, 2, 6])
[4, 2, 6]
###
There's a series of articles of functional programming using Python on
IBM's Developerworks web site:
http://www-106.ibm.com/developerworks/library/l-prog.html
http://www-106.ibm.com/developerworks/library/l-prog2.html
http://www-106.ibm.com/developerworks/library/l-prog3.html
Hey, there's some stuff here that I haven't seen before. Cool! *grin* I
think I'll take a closer look at this too.
> and i took a look @ the functional programming article in IBM's
> website. that was a good introduction.
Do you have a link to it? I'd like to take a look.
> Can someone tell me about other interesting sites that have a good
> discussion on functional programming...with examples.
If you're interested in functional programming, you might want to look at
the Haskell web site:
http://www.haskell.org/
Haskell is focused on functional programming, and I've heard that it's a
very good language for exploring functional ideas.
You may also find this link handy: I just found it on Google, and it looks
like good stuff:
http://www.cs.chalmers.se/~rjmh/tutorials.html