【发布时间】:2013-07-15 03:22:02
【问题描述】:
我在编程课上的一个任务是“河内塔”,我使用的语言是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 放在函数内,即使我在再次调用 towers-of-hanoi 函数之前执行了这 3 个操作 (setq tempPeg *Spare*) (setq *Spare* *Destination*) (setq *Destination* tempPeg) 但函数再次通过它的原始重新定义了 3 个变量价值。
2.)我想知道的是,我是否可以将 3 个变量的声明放在函数中,并且仍然能够防止函数为每个调用的递归重新定义相同的变量?
P/S 分配只允许我定义一个函数头,它接受磁盘作为唯一的参数,但不接受 Source 、 Spare 和 Destination rod。
【问题讨论】:
标签: variables recursion common-lisp