一旦执行该功能,如何在lisp中退出循环?

时间:2015-01-13 17:05:28

标签: function lisp common-lisp

我是LISP的初学者,希望你能为我解决我的困惑。我的代码如下:

(defun retrieve (element closed)
            (if (= (length closed) 0)
             (setf closedlist '(a))
              (dolist (count closed)
              (when (equal element (car count))
               (progn (check (childvalue (symbol-value count)) count) 
               (return)));;;endif
              );;;endouterloop
            )
           )

这是第一个函数,它将接受一个名为“element”的对象和一个名为“closed”的列表。下一个功能如下:

(defun check (child close)
           (setf tempvalue child)
           (dotimes (count (length tempvalue));;;1st loop
             (setf front (car tempvalue))
             (setf templist close)
             (dotimes (count1 (length close));;;2nd loop
               (if (= (length close) 1) 
                (if (string= front (car templist)) 
                    ((remove (nth count) child) (return));;;true
                    (setf templist (car templist));;;else
                 )
                 (if (string= front (car templist)) 
                    (setf child (remove (nth count child) child))
                    (setf templist (cdr templist));;;else
                   )
                 )
               );;;2nd loop
             (setf tempvalue (cdr tempvalue))
             );;;1stloop
           (format t "child ~S~%" child)
           )

我的问题是,从第一个函数开始,当我在第一个函数内部并且如果满足条件时,我将调用第二个函数(check)。但是,在我从第一个函数(检索)调用第二个函数(检查)并成功执行了操作之后,我想从第一个函数退出dotimes循环但是我不能这样做。

如果我尝试添加(返回)它,程序将退出循环,而不在语句中执行其他操作。在这种情况下,(check(childvalue(symbol-value temp))(第n次计数关闭))。

在调用辅助功能后,有人可以提供有关如何退出循环的任何建议吗?感谢。

1 个答案:

答案 0 :(得分:0)

if的格式为(if <condition> <if-true> <if-false>)

您撰写了(if <condition> (check ...) (break) ),因此break处于<if-false>位置,并在条件错误时首次关闭。要将多个语句分组为一个,请使用progn

(if (equal element temp)
    (progn (check (childvalue (symbol-value temp)) (nth count closed)) 
           (return)))

Progn除了group语句之外不会执行任何操作,并返回最后一个的结果。

您也可以使用when代替ifWhen的作用类似于(when <condition> <if-true>... )。它可以有多个if-trues但没有if-false。我认为这对你的情况很完美。

为了完整起见,when的反面是unless。它有多个if-falses而没有if-true。 (unless cond ...)相当于(when (not cond) ...)

SIDE-NOTE:作为旁注,将右括号放在同一行上,不要将)放在单独的行上。你的编辑应该为你缩进东西,然后通过缩进来查看和导航自己,忘记那些关闭的parens。一旦开始这样做,代码就会比许多传统语言更清晰。

第二面-NOTE: 如果你想要局部变量,使用let,或者你在某些实现中得到未声明的变量通知。示例:

(defun check (child close)
  (let ((tempvalue child)
        (front)
        (templist))
    (dotimes (count (length tempvalue))
      (setf front (car tempvalue))
      (setf templist close)
      (dotimes (count1 (length close))
        (if (= (length close) 1) 
            (if (string= front (car templist)) 
                ((remove (nth count) child) (return))
                (setf templist (car templist)))
            (if (string= front (car templist)) 
                (setf child (remove (nth count child) child))
                (setf templist (cdr templist)))))
      (setf tempvalue (cdr tempvalue)))
    (format t "child ~S~%" child)))