delay and force in Python

Will Stuyvesant hwlgw at hotmail.com
Mon Jan 24 05:17:25 EST 2005


Just for the record, an implementation without using generators,
somewhat like in Sect. 3.5 of the Wizard book, and without recursion
limit problems.
.
. def stream_hd(s): # the head of the stream
.     return s[0]
.
. def stream_tl(s): # the tail of the stream
.     return s[1]()
.
. ##
. # The low argument is required: the first element of the stream.
. # You either use high= or stop_f= to define the end of the
. # stream.  Omit both for an infinite stream.  stop_f is a function
. # that takes low as argument and returns True or False.
. # The next_f function takes one argument (an element of the stream,
. # same type as the low argument has)
. # The stop_f function takes one argument (same type as low)
. # @param low object
. # @param high object
. # @param next_f function
. # @param stop_f function
. # @return list, a stream
. def make_stream(low, high=None, next_f=None, stop_f=None):
.     if next_f is None: next_f = lambda x: x + 1
.     if high is not None:        # using high
.         if low > high:
.             return None
.         else:
.             return [low, lambda: make_stream(
.               next_f(low), high=high, next_f=next_f)]
.     elif stop_f is not None:    # using stop_f
.         if low > stop_f(low):
.             return None
.         else:
.             return [low, lambda: make_stream(
.               next_f(low), next_f=next_f, stop_f=stop_f)]
.     else:                       # infinite stream
.         return [low, lambda: make_stream(
.               next_f(low), next_f=next_f)]
.
. ##
. # iterative version of filter
. # @param pred function, (stream-element) -> bool
. # @param s list, a stream
. # @return list, a stream
. def stream_filter(pred, s):
.     if s is None: return []
.     while True:
.         elem = stream_hd(s)
.         if pred(elem):
.             return [elem, lambda: stream_filter(pred, stream_tl(s))]
.         else:
.             s = stream_tl(s)
.             if s is None: return []
.
.
. if __name__ == '__main__':
.
.     def is100some(x): return x % 100 == 0
.     assert(stream_hd(stream_tl(stream_tl(stream_filter(
.         is100some,
.         make_stream(1, 11111111111111))))) == 300)
.
.     def add_33(x): return x + 33
.     assert(stream_hd(stream_tl(stream_filter(
.         is100some,
.         # stream 1,34,67,100,...
.         make_stream(1,999999999, next_f = add_33)))) == 3400)
.
.     assert(stream_hd(stream_tl(stream_filter(
.         is100some,
.         # infinite stream 1,2,...
.         make_stream(1)))) == 200)
.
.     def mod_20000(x): return x % 20000 == 0
.     # this will need more evaluations than the recursion limit count
.     infinite_filter = stream_filter(mod_20000, make_stream(1))
.     assert( stream_hd(stream_tl(infinite_filter)) == 40000 )
.




More information about the Python-list mailing list