DEV Community

Discussion on: Understanding Recursion and Continuation with Python

Collapse
 
mike239x profile image
Mike Lezhnin

I think I understood it, but the example with continuations is still quite mind-blowing.
I probably would have rewritten it like so:

import traceback

def fib_cnt ( state ) :
    print(len(traceback.extract_stack()) * '*' + ": " + str(state))
    if state['finished'] :
        return state
    if len(state['values']) == 0 :
        state['finished'] = True
        return state
    n = state['values'].pop()
    if n < 2:
        state['acc'] += 1
        return state
    state['values'].append(n-1)
    state['values'].append(n-2)
    return state

def fib (n) :
    state = dict ( values = [n], acc = 0, finished = False )
    while not state['finished'] :
        state = fib_cnt(state)
    return state['acc']

print(fib(5))

This way most of the state is quite transparent and not hidden behind lambdas.