[Tutor] Speaking of Linked Lists...

VanL vlindberg@verio.net
Tue, 20 Mar 2001 15:24:44 -0700


Here is one sort of useless, sort of cool application:
This can represent any infinite series.  Right now compute_nextval is such
that it computes the Fibonacci series, but that can be overloaded or replaced
with whatever you might like.


class InfiniteList:

    """ This is an implementation of an infinite list, where the next() method
computes and caches the
    result of a series of calculations of an infinite list. """

    def __init__(self, index=1, value=1, objprev=None):
        self.__index = index
        self.__value = value
        self.__nextlink = None
        if objprev: self.__prevlink = objprev
        else: self.__prevlink = self

    def next(self):
        if (self.__nextlink): return self.__nextlink

        else:
            nextind = self.__index + 1
            nextval = self.compute_nextval()
            self.__nextlink = InfiniteList_Fib(nextind, nextval, self)
            return self.__nextlink

    def prev(self):
        if self.__prevlink: return self.__prevlink
        else: return None

    def index(self):
        return self.__index

    def value(self):
        return self.__value

    def unlink(self):
        self.__prevlink = None
        self.__nextlink = None

    def compute_nextval(self):
        val = self.__value + (self.__prevlink).__value
        return val