Return 来自条件循环

Return from a loop on a condition

我有以下功能:

(defun chooseBest (TSPs dTSPs)
    (let ((minim (minPos dTSPs 0 0)) (j 0) (best nil)) 
        (loop for i in TSPs
             do (cond ((= j minim) (progn (setf best i) (setq j (+ j 1))))
                      (t (setq j (+ j 1)))))        
        best))

这个函数接收两个列表:

TSPs - 像这样的路径列表:

(((1 3600 2300) (2 3100 3300))
 ((3 4700 5750) (22 6650 2300) (23 5400 1600)))

以及与这些相关的距离列表:

(distancePath1 distancePath2)

函数minPos return是list中数字小的位置,也就是距离小的路径

鉴于此,chooseBest 函数将 return 较小的路径。

但我想改进它,因为它会在整个列表中搜索较小的数字,这很浪费,因为 minim 有那个位置。例如 minim 是 2,但它正在评估具有 100 条路径的 TSP 列表,我想 return 立即在 2 上并中断循环,但是 return 不起作用...

如果你想要列表的第nth个元素,你可以使用函数nth(nth position list)

CL-USER 15 > (nth 0 '(((1 3600 2300) (2 3100 3300))
                      ((3 4700 5750) (22 6650 2300) (23 5400 1600))))
((1 3600 2300) (2 3100 3300))

CL-USER 16 > (nth 1 '(((1 3600 2300) (2 3100 3300))
                      ((3 4700 5750) (22 6650 2300) (23 5400 1600))))
((3 4700 5750) (22 6650 2300) (23 5400 1600))

如果要从循环中 return,可以使用运算符 return:

CL-USER > (loop for i from 10
                when (= i (expt (isqrt i) 2))
                do (return i))
16

让我们稍微修改一下您的函数。

首先,更好的缩进:

(defun chooseBest (TSPs dTSPs)
  (let ((minim (minPos dTSPs 0 0))
        (j 0)
        (best nil))
    (loop for i in TSPs
       do (cond ((= j minim)
                 (progn (setf best i)
                        (setq j (+ j 1))))
                (t 
                 (setq j (+ j 1)))))
    best))

不需要cond里面的progn:

       do (cond ((= j minim)
                 (setf best i)
                 (setq j (+ j 1)))
                (t 
                 (setq j (+ j 1)))))

增加 j 可以用 incf:

                 (setq j (+ j 1)))

=>

                 (incf j)

您可以将 let 变量 移动到 循环 中。

  (let ((minim (minPos dTSPs 0 0))
        (j 0)
        (best nil))
    (loop for i in TSPs

=>

(loop for it in TSPs
      for j from 0
      with minim = (minPos dTSPs 0 0)
      with best
      do …)

for j from 0 启动一个计数器,with … = 声明一个在开始时计算的变量(而不是在每次迭代时)。

Returns 和条件

在一个循环中,我们可以多次使用if…doelse…dowhenreturn。要在循环结束时执行某些操作,请使用 finally.

(defun chooseBest (TSPs dTSPs)
  (loop for i in TSPs
     for j from 0
     with minim = (minPos dTSPs 0 0)
     with best
     if (= j minim)
     do (progn (setf best i)
               (incf j))
     else
     do (incf j)
     finally (return best)))

搜索列表和序列的函数

现在,如果您想在列表中查找一个元素,您可以使用很多函数:查找、第 n 个、搜索、位置……参见 https://lispcookbook.github.io/cl-cookbook/data-structures.html#functionsminPos returns 索引,您可能需要 nth index listelt sequence index.