對於一個任務,我有一個名爲光盤Common Lisp的創建河內塔。我需要輸出看起來是這樣的:塔樓命名光盤
[1]> (hanoi '(Small Medium Large))
Moved SMALL from Peg 1 to Peg 3
Moved MEDIUM from Peg 1 to Peg 2
Moved SMALL from Peg 3 to Peg 2
Moved LARGE from Peg 1 to Peg 3
Moved SMALL from Peg 2 to Peg 1
Moved MEDIUM from Peg 2 to Peg 3
Moved SMALL from Peg 1 to Peg 3
NIL
[2]> peg1
NIL
[3]> peg2
NIL
[4]> peg3
(Small Medium Large)
然而,當我跑我已創建的程序,我得到的輸出是這樣的:
[1]> (hanoi '(Small Medium Large))
Move SMALL from Peg 1 to Peg 2
Move SMALL from Peg 1 to Peg 2
Move NIL from Peg 2 to Peg 2
Move SMALL from Peg 1 to Peg 2
Move NIL from Peg 2 to Peg 1
Move NIL from Peg 2 to Peg 2
Move SMALL from Peg 1 to Peg 2
NIL
[2]> peg1
(Small Medium Large)
[3]> peg2
NIL
[4]> peg3
NIL
這裏是我的代碼:
(defvar *peg1* '())
(defvar *peg2* '())
(defvar *peg3* '())
(defun peg-name (peg)
(cond ((equal peg *peg1*) "Peg 1")
((equal peg *peg2*) "Peg 2")
((equal peg *peg3*) "Peg 3")))
(defun move-disk (from to)
(format t "Move ~a from ~a to ~a~%" (first from) (peg-name from) (peg-name to))
(push (pop from) to))
(defun transfer (n source aux dest)
(if (> n 0)
(progn
(transfer (1- n) source dest aux)
(move-disk source dest)
(transfer (1- n) aux source dest))))
(defun hanoi (disk-list)
(setq *peg1* disk-list)
(transfer (length disk-list) *peg1* *peg2* *peg3*))
與代碼的問題顯然是移動磁盤功能,因爲它只是扔掉結果它被稱爲後。但我不確定我究竟能夠確定哪些全局變量是我應該推動並從中彈出的。我用一個大的列表來代替塔,並把樁作爲子列表,但我有同樣的問題來確定要修改的列表的哪一部分。任何幫助,將不勝感激。我覺得我處於一個完全死角。
'push'和'pop'是Common Lisp中的標準宏。 –
@EliasMårtenson:大聲笑LISP太生鏽了_ _ < – hugomg