public
Created

Lazy functional style streams for Python

  • Download Gist
streams.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
null_stream = (None, None)
 
def map(f, stream):
if stream is null_stream: return null_stream
return (f(head(stream)), lambda: map(f, tail(stream)))
 
def reduce(f, result, stream):
if stream is null_stream: return result
return reduce(f, f(result, head(stream)), tail(stream))
 
def take(N, stream):
if N <= 0 or stream is null_stream: return null_stream
return (head(stream), lambda: take(N-1, tail(stream)))
 
def to_array(stream):
return reduce(lambda a, x: a + [x], [], stream)
 
def filter(pred, stream):
if stream is null_stream: return null_stream
if pred(head(stream)):
return (head(stream), lambda: filter(pred, tail(stream)))
return filter(pred, tail(stream))
 
def sieve(stream):
if stream is null_stream: return null_stream
h = head(stream)
return (h, lambda: sieve(filter(lambda x: x%h != 0, tail(stream))))
 
def head((H, _)): return H
 
def tail((_, T)): return T()
 
def integers_from(N): return (N, lambda: integers_from(N+1))
 
def rec_stream(f):
return (f, lambda: rec_stream(lambda x: f(f(x))))
 
def newton(f, fdash):
return lambda x: x - f(x)/float(fdash(x))
 
def newton_solver(iters, f, fdash):
def solve(v):
n = newton(lambda x: f(x) - v, fdash)
stream = rec_stream(n)
return to_array(take(iters, stream))[-1]
return solve

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.