2

今日、以下のコードをschemeで書きましたが、評価が間違っています。私がプログラミングが苦手だとは言わないでください。これが古典的な再帰問題であることは理解していますが、問題が発生しています。

(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))))

コードが機能することを期待していましたが、デバッグするとさらに混乱してしまいます。誰でも私を助けることができますか?

4

1 に答える 1

4

あなたのコードでは、最後の再帰呼び出しが間違っているようで、プロシージャのパラメータの順序に問題があります。代わりにこれを試してください:

(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))))

あなたが のタグが付いた質問をしていることに気付きましたracket。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)]))

いずれにせよ、期待どおりに動作します。

(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
于 2013-12-05T01:27:34.543 に答える