( The Towers Of Hanoi ) ( FORTH ) ( Copyright 1998 Amit Singh. All Rights Reserved. ) ( http://hanoi.kernelthread.com ) ( ) ( Tested under GNU Forth 0.3.0, PFE 0.9.14 ) ( Use "gforth -e 'n HANOI bye'" to run ) ( hanoi with n disks. Alternatively, load everything ) ( and use the HANOI word from within the interpreter. ) : MOVEIT ." move " . ." --> " . CR ; ( to from -- ) : DOHANOI ( to from using n -- ) ( T3 <- T1 using T2 ) DUP 0 > ( more disks ? ) IF 1 - ( n <- n - 1 ) 2OVER 2OVER ( clone data stack ) >r >r >r >r ( save it to rstack ) 1 ROLL 2 ROLL 3 ROLL 3 ROLL ( using from to n-1 ) RECURSE ( T2 <- T1 using T3 ) 2r@ SWAP MOVEIT ( to from ) 2DROP 2DROP ( empty the stack ) 2r> 2r> ( from to n-1 using ) SWAP ( from to using n-1 ) 3 ROLL ( to using n-1 from ) SWAP ( to using from n-1 ) RECURSE ( T3 <- T2 using T1 ) THEN ; : HANOI ( n -- ) ( prepare arguments ) 3 1 2 3 ROLL DOHANOI 2DROP 2DROP ;