プログラミング クラスでの私の課題の 1 つは「ハノイの塔」です。使用していた言語は Common Lisp で、ソース コードは次のとおりです。
コード :
変数:
(defparameter *Source* "Peg 1")
(defparameter *Spare* "Peg 2")
(defparameter *Destination* "Peg 3")
上記の変数宣言を関数内に入れたい
(defun towers-of-hanoi (disks)
;disks accept list as parameter , for e.g `(s m l)
(let ((tempPeg))
(if (= (list-length disks) 1)
(format t "Move ~{~A~} from ~A to ~A~%"
(last disks) *Source* *Destination*)
(progn
(setq tempPeg *Spare*)
(setq *Spare* *Destination*)
(setq *Destination* tempPeg)
(towers-of-hanoi (subseq disks 0 (- (list-length disks) 1)))
(setq tempPeg *Spare*)
(setq *Spare* *Destination*)
(setq *Destination* tempPeg)
(format t "Move ~{~A~} from ~A to ~A~%"
(last disks) *Source* *Destination*)
(setq tempPeg *Spare*)
(setq *Spare* *Source*)
(setq *Source* tempPeg)
(towers-of-hanoi (subseq disks 0 (- (list-length disks) 1)))
(setq tempPeg *Spare*)
(setq *Spare* *Source*)
(setq *Source* tempPeg)
(format t "")))))
質問 :
1.) この問題を解決するために再帰アルゴリズムを使用しています。このアルゴリズムでわかっているように、3 つの変数 (ソース、スペア、宛先) は (いくつかの規則によって) 相互に交換する必要があります。defvar
関数内に を配置する(setq tempPeg *Spare*)
(setq *Spare* *Destination*)
(setq *Destination* tempPeg)
と、towers-of-hanoi 関数を再度呼び出す前にこの 3 つの操作を実行しますが、関数は再び 3 つの変数を元の値に再定義します。
2.) 私が知りたかったのは、関数内に 3 つの変数の宣言を配置し、関数が呼び出される再帰ごとに同じ変数を再定義するのを防ぐことができるかということです。
P/S 割り当てでは、ディスクを唯一の引数として受け入れる関数ヘッダーのみを定義できますが、 Source 、 Spare 、および Destination ロッドは受け入れません。