recursion - 优化 Lisp 递归随机游走

标签 recursion optimization lisp clisp

此函数导致堆栈溢出超过 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))))

由于我没有您使用的功能,所以除了基本情况外,我无法对其进行测试。

关于recursion - 优化 Lisp 递归随机游走,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46856492/

相关文章:

lisp - defun 以列表作为参数

web-services - 使用 Lisp 的 Web 服务

复制树结构时出现 java.util.ConcurrentModificationException

javascript - 使用递归到达嵌套数组项 - javascript

regex - 更有效的正则表达式来解析 linux 顶级命令值

c++ - boost 压缩矩阵基础知识

recursion - Elixir map_reduce 引用最后一个元素

algorithm - 最短根到叶路径

memory - 您可以获得多接近 GPU 理论内存带宽?

unix - unix 脚本最好的 lisp/scheme 是什么?