Skip to content

Instantly share code, notes, and snippets.

@scturtle
Last active August 29, 2015 14:12
Show Gist options
  • Save scturtle/f54b7e733b26c048d404 to your computer and use it in GitHub Desktop.
Save scturtle/f54b7e733b26c048d404 to your computer and use it in GitHub Desktop.
factorial function in CPS
def bounce(func, *args):
return ('bounce', func, args)
def land(value):
return ('land', value)
def pogo(bouncer):
''' Keep bouncing until landing. '''
while True:
if bouncer[0] == 'land':
return bouncer[1]
else: # 'bounce'
bouncer = bouncer[1](*bouncer[2])
##########################################################################
# 1. trampolined style
def fac_t(n, k=1):
return land(k) if n == 0 else bounce(fac_t, n - 1, k * n)
print pogo(fac_t(5))
# 2. continuation-passing style
def fac_k(n, k):
return k(1) if n == 0 else\
fac_k(n - 1, lambda f: k(n * f))
print fac_k(5, lambda n: n)
# 3. trampolined continuation-passing style
def fac_tk(n, k):
return bounce(k, 1) if n == 0 else\
bounce(fac_tk, n - 1, lambda f: bounce(k, n * f))
print pogo(fac_tk(5, lambda n: land(n)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment