首页 > 解决方案 > 不要循环,迭代!(普通 Lisp)

问题描述

我无法切换到某些循环代码的迭代版本:

(defun get-bound-?vars-1 (tree)
  (loop for item in tree
        when (consp item)
          if (member (car item) '(exists forall doall))
            nconc (delete-if-not #'?varp
                    (alexandria:flatten (second item)))
            else nconc (get-bound-?vars item)))

我相应的迭代翻译:

(defun get-bound-?vars-2 (tree)
  (iter (for item in tree)
        (when (consp item)
          (if (member (car item) '(exists forall doall))
            (nconc (delete-if-not #'?varp
                     (alexandria:flatten (second item))))
            (nconc (get-bound-?vars item))))))

作为测试用例:

(defparameter *tree* 
  '(if (exists (?t transmitter)
         (and (connecting ?t ?connector)
              (bind (color ?t $hue))))
     (if (not (exists ((?t1 ?t2) transmitter)
                (and (connecting ?t1 ?connector)
                     (connecting ?t2 ?connector)
                     (bind (color ?t1 $hue1))
                     (bind (color ?t2 $hue2))
                     (not (eql $hue1 $hue2)))))
       (activate-connector! ?connector $hue))))

然后循环确定:

(get-bound-?vars-1 *tree*) => (?T ?T1 ?T2)

但迭代不行:

(get-bound-?vars-2 *tree*) => NIL

感谢您的任何指示。

标签: loopsfor-loopcommon-lisp

解决方案


推荐阅读