hanoi-story Pub

The towers of Hanoi - classic recursion example

See en.wikipedia.org/wiki/Tower_of_Hanoi for a detailed intro, if you're not familiar with this classic recurrence problem.

Good example

Set the towers as variables, ahead of calling the function, in the global context:

send::  msg ctx.set  (state:JSON={a:[0,1,2,...)

Now call the recursion:

send::  msg sample.hanoi  (disk:Number=3=3, source="a"="a", dest="b"="b", aux="c"="c")

send::  msg ctx.echo  (m=state)

expect::  (state[="a"] is [4,5])
expect::  (state[="b"] is [0,1,2,3])

Bad example:

This simplistic example would not work, because the parameters are immutable. To be able to mutate the contents of the incoming arguments, you'll need a global scope like we used in the "good" example above, with ctx.set.

send::  msg sample.hanoi.bad  (disk:Number=3=3, source:Array=[0,1,2,3], dest:Array=[], aux:Array=[])

Was this useful?    

By: Razie | 2019-05-29 .. 2022-03-17 | Tags: story , dsl , sanity

Viewed 312 times ( | History | Print ) this page.

You need to log in to post a comment!

© Copyright DieselApps, 2012-2022, all rights reserved.