这个函数导致堆栈溢出超过大约2000步,有没有什么方法可以轻松优化它以减少内存使用?
(defun randomwalk (steps state)
(displaystate state)
(if (equal steps 0) nil
(if (solved? state) t
(let ((nrmlstate (normalize state)))
(randomwalk (- steps 1) (applymove nrmlstate (nth (random
(length (getallmoves nrmlstate))) (getallmoves nrmlstate))))
)
)
)
)
答案 0 :(得分:2)
看起来你只能在尾部位置调用,这意味着你可以轻松地将其重写为完全没有递归:
(defun randomwalk (steps state)
(loop :if (= steps 0)
:do (return nil)
:if (solved? state)
:do (return t)
:else
:do (let* ((nrmlstate (normalize state))
(moves (getallmoves nrmlstate))
(random-move (nth (random (length moves)) moves)))
(setf state (applymove nrmlstate random-move))
(decf steps))))
由于我没有您使用的功能,除了基本情况之外,我还无法测试它。