优化 Lisp 递归随机游走
Optimize Lisp recursive random walk
此函数导致堆栈溢出超过 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))))
)
)
)
)
看起来你只在尾部位置调用,这意味着你可以轻松地重写它以完全不递归:
(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))))
由于我没有您使用的功能,所以除了基本情况外,我无法对其进行测试。
此函数导致堆栈溢出超过 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))))
)
)
)
)
看起来你只在尾部位置调用,这意味着你可以轻松地重写它以完全不递归:
(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))))
由于我没有您使用的功能,所以除了基本情况外,我无法对其进行测试。