functional programming

Felix Thibault felixt at dicksonstreet.com
Wed Feb 23 21:44:32 EST 2000


At 02:00 2/24/00 +1100, Jason Stokes wrote:
>
>Remco Gerlich wrote in message ...
>>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 example exploits lazy evaluation.  Since Python is strict, like most
>procedural languages, it isn't possible to produce this in Python.
>
>
>-- 
>http://www.python.org/mailman/listinfo/python-list
>
>

Isn't this more or less the same thing, except that it's not as terse?:

import UserList
class LyinLazyFibber(UserList):
    def more(self, now, goal):
        sofar = self.data
        nexttolast, last = sofar[-2:]
        for next in range(goal - now):
            next = last + nexttolast
            sofar.append(next)
            nexttolast, last = last, next
        self.last = goal
        
    def __getitem__(self, index):
        if index < 0:
            raise "CantGetThereFromHere"
        if index > self.last:
            self.more(self.last, index)
        return self.data[index]
        
    def __getslice__(self, left, right):
        if right < 0:
            raise "NotInThisLifetime"
        if right > self.last:
            self.more(self.last, right)
        return self.data[left:right]
        
    def __init__(self, first2=None):
        if first2 is None:
            self.data = [1,1]
        elif len(first2) != 2:
            raise ValueError, "value must be a list of 2 numbers"
        else:
            try:
                test = first2[0] + first2[1]
            except:
                raise TypeError, "objects %s %s cannot be added" %
tuple(first2)
            else:
                self.data = list(first2)
        self.last = 1






More information about the Python-list mailing list