LISP 回溯

发布于 2024-11-27 01:33:07 字数 86 浏览 3 评论 0原文

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

谢谢

Can someone please guide me or explain how to perform backtracking in LISP ? Any examples or links would be appreciated.
I did try to google , however none of them had simple example enough for me to understand.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那片花海 2024-12-04 01:33:07

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

一个可能的(尽管不是最理想的)数独求解器将是:

;;; 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)))))))))

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

The typical way is to have non-mutable state passed down the call-stack, with helper functions taking the current state-returning a new state to "fake" mutation.

A possible (although rather suboptimal) sudoku-solver would then be:

;;; 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)))))))))

This will automatically backtrack until a solution is found. I have skipped obscuring the demonstration with the support code that would turn it from a demonstration to actual working code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文