> (delay (/ 1 0))

#<promise>

> (force (delay (/ 1 0)))

division by zero

class Promise(object):



"""This is a promise to execute something on demand."""



def __init__(self, f):

"""Wrap your expression in a lambda and pass it as f."""

self.f = f



def __call__(self):

"""Call the instance to get the value of the promise.



This is memoized so that it doesn't have to compute the value

more than once since promises shouldn't do that.



"""

if not hasattr(self, 'result'):

self.result = self.f()

return self.result





promise = Promise(lambda: 1 / 0)

print repr(promise)

print "No error yet."

print "Now, we'll force the promise, causing the error."

promise()

def generator(start=0):

while True:

yield start

start += 1





for i in generator():

print i

def generator(start=0):

scope = locals()



def top():

while True:

return scope['start'], bottom



def bottom():

scope['start'] += 1

return top()



return top





next = generator()

while True:

(i, next) = next()

print i

I just finished the lecture on streams in SICP . Python has generators, which are quite lovely. However, it's fun to imagine reimplementing generators in various ways from scratch using some of the approaches in SICP.First of all, there are promises. A promise says that you'll do something later. In Scheme, you create a promise with "delay" and you invoke that promise with "force":Here's one way to translate that to Python:Easy :)Now, let's take a look at a generator. Here's a simple counter:Clearly, you can do this with an iterator class. However, let's instead use a closure and continuation passing style. The syntax isn't the most beautiful in the world, but it definitely does the trick ;)