Solving the problem of mutual recursion

Roy Smith roy at panix.com
Sun May 26 11:23:04 EDT 2013


In article <qota9nhu6ag.fsf at ruuvi.it.helsinki.fi>,
 Jussi Piitulainen <jpiitula at ling.helsinki.fi> wrote:

> A light-weighter way is to have each task end by assigning the next
> task and returning, instead of calling the next task directly. When a
> task returns, a driver loop will call the assigned task, which again
> does a bounded amount of work, assigns the next task, and returns.
> Tasks can even pass parameters in the same way.

Yup.  I've used this pattern for building state machines.  Each state is 
a function which returns the next state (or, sometimes, a (next_state, 
output) tuple).  The top level loop ends up looking very much like yours:

state = start
while state != end:
   state, output = state(get_next_input())
   print output


> 
> Like so, Dr. Fred keeps adding to a pile as long as there is a pile,
> and Mr. Jim keeps taking from it as long as it's there to take from:
> 
> from random import choice
> 
> def fred():
>     global fun, arg
>     print('Fred adds 1')
>     fun, arg = choice((fred, jim)), arg + 1
> 
> def jim():
>     global fun, arg
>     print('Jim takes 1')
>     fun, arg = choice((fred, jim)), arg - 1
> 
> if __name__ == '__main__':
>     fun, arg = choice((fred, jim)), 3
>     while arg:
>         print('Pile is', arg, end = '\t')
>         fun()
>     else:
>         print('Pile is gone')



More information about the Python-list mailing list