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":
> (delay (/ 1 0))Here's one way to translate that to Python:
> (force (delay (/ 1 0)))
division by zero
class Promise(object):Easy :)
"""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
"""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()
promise = Promise(lambda: 1 / 0)
print "No error yet."
print "Now, we'll force the promise, causing the error."
Now, let's take a look at a generator. Here's a simple counter:
def generator(start=0):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 ;)
start += 1
for i in generator():
scope = locals()
return scope['start'], bottom
scope['start'] += 1
next = generator()
(i, next) = next()