LISP 回溯

标签 lisp common-lisp

有人可以指导我或解释如何在 LISP 中执行回溯吗?任何示例或链接将不胜感激。 我确实尝试过谷歌,但是他们都没有足够简单的例子让我理解。

谢谢

最佳答案

典型的方法是将不可变状态向下传递到调用堆栈,辅助函数采用当前状态 - 将新状态返回到“假”突变。

一个可能的(虽然不是最优的)数独求解器将是:

;;; Use a list of 81 integers to represent a sudoku board,
;;; each number 1-9 represents itself, 0 represents a blank
(defun sudoku-solver (board)
  (cond ((notany #'zerop board)
     (if (sudoku-solved-p board)
         board
         nil))
    (t (let ((positions (sudoku-all-blanks board)))
         (loop for position in positions
          do (loop for number in '(1 2 3 4 5 6 7 8 9)
              do (let ((result (sudoku-solver
                        (sudoku-set board
                            position
                            number))))
                   (when result
                 (return-from sudoku-solver result)))))))))

这将自动回溯,直到找到解决方案。我已经跳过使用支持代码来掩盖演示,支持代码会将其从演示转变为实际工作代码。

关于LISP 回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6842070/

相关文章:

emacs - 开发中如何在SLIME中快速重新加载和重启

lisp - 为什么将 "(null x)"替换为 "(null (cdr x))"会使此代码有效?

lisp - 在 Linux 中安装 SBCL

lisp - 从嵌套列表中删除

lisp - lisp有什么不同

list - 方案 - 追加到列表的末尾

parsing - Prolog 中的 DCG — 字符串

list - 如何删除包含两个您不想要的元素的列表中的元素?

Qt(通过 Common Lisp 的 qtools): QLineEdit does not activate on click but receives focus on TAB

lisp - 成员函数在 cons 结构中不起作用