【问题标题】:Why setq cuts my list为什么 setq 削减我的名单
【发布时间】:2014-10-20 05:30:41
【问题描述】:

正如标题所说,我正在尝试将项目附加到一个名为解决方案的列表中,下面是代码:

(defun add-solution (n)
    (let ((solution)) 
        (do((current-node '() (next-state current-node n nil)))
            ((equal current-node '(0 0 0 0)) solution)
            (if (goal-test current-node n)
                (progn
                    (format t "Cur: ~S~%" current-node)
                    (setq solution (append solution (list current-node)))
                    (format t "Solution: ~S~%" solution)
                )
            )   
        )
    )
)

每次新的当前节点都类似于:(1 7 8 14), (2 4 11 13), 但当循环返回时returns ((1) (2)).. 我需要的是(((1 7 8 14) (2 4 11 13))。不知道那里发生了什么??

编辑: 我在setq之前和之后添加了格式函数,输出如下:


Cur: (1 7 8 14)
Solution: ((1 7 8 14))
Cur: (2 4 11 13)
Solution: ((1)(2 4 11 13))

整个事情完成后,返回值再次变为((1) (2))。我并没有真正做任何修改solution...

【问题讨论】:

  • 您的代码似乎没有任何问题(样式问题除外,例如缩进)。所以,问题可能出在next-state 函数中——也许它正在破坏性地修改它的第一个参数 (current-node),导致已经收集的节点变得无效?
  • 是的。解决了我的问题..非常感谢!这让我发疯:/

标签: lisp common-lisp


【解决方案1】:

看起来你的错误在其他地方。

风格:

我会这样编写/格式化代码:

(defun add-solution (n)
  (do ((solution nil)
       (current-node '() (next-state current-node n nil)))
      ((equal current-node '(0 0 0 0)) solution)
    (when (goal-test current-node n)
      (setq solution (append solution (list current-node))))))

请注意,这是错误代码,因为您在循环中追加一个项目到列表的末尾。这是一个潜在的非常昂贵的操作。 Lisp 列表针对添加到前面而不是末尾进行了优化。

【讨论】:

  • 感谢您的造型建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 2012-06-28
  • 1970-01-01
相关资源
最近更新 更多