Towers of Hanoi in Scheme (recursive)

妖精的绣舞 提交于 2019-12-22 18:30:20

问题


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?


回答1:


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:

(define (towers-of-hanoi n source dest temp)
  (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 dest source))))

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:

(define (towers-of-hanoi n source dest temp)
  (cond [(= n 1)
         (printf "Move the disk from ~a to ~a~n" source dest)]
        [else
         (towers-of-hanoi (sub1 n) source temp dest)
         (printf "Move the disk from ~a to ~a~n" source dest)
         (towers-of-hanoi (sub1 n) temp dest source)]))

Either way, it works as expected:

(towers-of-hanoi 3 "source" "dest" "temp")

Move the disk from source to dest
Move the disk from source to temp
Move the disk from dest to temp
Move the disk from source to dest
Move the disk from temp to source
Move the disk from temp to dest
Move the disk from source to dest


来源:https://stackoverflow.com/questions/20389382/towers-of-hanoi-in-scheme-recursive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!