functional programming
Robin Becker
robin at jessikat.demon.co.uk
Wed Feb 23 16:22:04 CET 2000
In article <slrn8b79dc.958.scarblac-spamtrap at flits104-37.flits.rug.nl>, Remco Gerlich <scarblac-
spamtrap at pino.selwerd.nl> writes
>Michal Wallace (sabren) wrote in comp.lang.python:
>> I guess my original question had to do with what functional
>> programming looks like in the wild, and what it might look like in
>> python. Aahz posted a recursive version of a fib() routine. Is this
>> not what you'd want? What would fib() look like in one of the
>> functional languages you're used to?
>
>Michael Hudson posted this little bit of Haskell last week:
>
>fib = 1 : 1 : [ a+b | (a,b) <- zip fib (tail fib) ]
>
>I can't translate that to anything resembling Python at all. I don't
>know if list comprehensions in Python will be/are this powerful.
>(This is just a definition of the infinite list of Fibonacci numbers -
>when you need the first 50 or so, just take the first 50 from this list).
>
>
#Joe Bowbeer posted this recently SICP
def head(s): # return first element in stream
return s and s[0]
def tail(s): # return remainder of stream
return s and s[1] and s[1]()
def addStreams(si, sj): # add corres. elements of two streams
if not si: return sj
if not sj: return si
tailsum = lambda ti=si, tj=sj : addStreams(tail(ti), tail(tj))
return (head(si) + head(sj), tailsum)
def nthStream(s, n): # return nth element of stream s
while n > 0:
s, n = tail(s), n-1
return head(s)
def printStream(s, n): # print first n elements of stream s
while n > 0:
print head(s),
s, n = tail(s), n-1
print
def mapStream(f,s):
return (apply(f,[head(s)]), lambda f=f, s=s: mapStream(f,tail(s)))
# then
# infinite stream of Fibonacci numbers
fibs = (0, lambda : (1, lambda : addStreams(tail(fibs), fibs)))
printStream(fibs, 10)
--
Robin Becker
More information about the Python-list
mailing list