Skip to content

Instantly share code, notes, and snippets.

@scturtle
Last active August 29, 2015 14:12
Show Gist options
  • Save scturtle/8fa79ba5d3f4f8cfb316 to your computer and use it in GitHub Desktop.
Save scturtle/8fa79ba5d3f4f8cfb316 to your computer and use it in GitHub Desktop.
Trampolined-style (workaround of tail recursion) http://lifegoo.pluskid.org/?p=327
calling tramp_fac(n=5, k=1)
bouncer: ('bounce', 'tramp_fac', (4, 5))
calling tramp_fac(n=4, k=5)
bouncer: ('bounce', 'tramp_fac', (3, 20))
calling tramp_fac(n=3, k=20)
bouncer: ('bounce', 'tramp_fac', (2, 60))
calling tramp_fac(n=2, k=60)
bouncer: ('bounce', 'tramp_fac', (1, 120))
calling tramp_fac(n=1, k=120)
bouncer: ('bounce', 'tramp_fac', (0, 120))
calling tramp_fac(n=0, k=120)
bouncer: ('land', 120)
120
def bounce(func, *args):
return ('bounce', func, args)
def land(value):
return ('land', value)
def pogo(bouncer):
''' Keep bouncing until landing. '''
while True:
print 'bouncer:',
if bouncer[0] == 'land':
print bouncer
return bouncer[1]
else: # 'bounce'
print (bouncer[0], bouncer[1].func_name, bouncer[2])
bouncer = bouncer[1](*bouncer[2])
def tramp_fac(n, k=1):
print 'calling tramp_fac(n={}, k={})'.format(n, k)
if n == 0:
return land(k)
else:
return bounce(tramp_fac, n - 1, k * n)
print pogo(tramp_fac(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment