I wrote the following code in scheme today, but the evaluation is wrong. Please don't tell me I suck at programming, I understand that this is a classic recursion problem, but I am having trouble with it:
(define (towers-of-hanoi n source temp dest)
(if (= n 1)
(begin (display "Move the disk from ")
(display source)
(display " to " )
(display dest)
(newline))
(begin (towers-of-hanoi (- n 1) source temp dest)
(display "Move the disk from ")
(display source)
(display " to ")
(display dest)
(newline)
(towers-of-hanoi(- n 1) temp source dest))))
I expected the code to work, and when I debug it I just confuse myself even more. Can anyone help me?
In your code, the last recursive call appears to be wrong, and there is a problem with the order of the procedure's parameters. Try this instead:
I noticed that you've been asking questions tagged as
racket
, here's a more idiomatic and shorter version of the same code, for Racket:Either way, it works as expected: