hanoi-story Pub

The towers of Hanoi - classic recursion example

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,3,4,5],b:[],c:[]})

Now call the recursion:

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

send::  msg ctx.echo  (m<-state)

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

important take-aways:

  • from js expr you can't affect state outside js:state.aux.push(3) won't work

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.

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

Was this useful?    

By: Razie | 2019-05-29 | Tags: story , dsl

Viewed 85 times ( | Print ) this page.

You need to log in to post a comment!

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