首页 > 解决方案 > 根据条件从循环返回

问题描述

我有以下功能:

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

该函数接收两个列表:

TSP - 类似这样的路径列表:

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

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

(distancePath1 distancePath2)

该函数minPos返回具有较小数字的列表的位置,即距离较小的路径。

鉴于此,该chooseBest函数将返回较小的路径。

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

标签: lispcommon-lisp

解决方案


让我们稍微修改一下你的功能。

首先,具有更好的缩进

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

不需要progn内部cond

       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 … =声明一个在开始时计算的变量(而不是在每次迭代时)。

返回和条件

在循环中,我们可以多次使用if…do, else…do, whenand , and 。return要在循环结束时执行某些操作,请使用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)))

搜索列表和序列的功能

现在,如果您想在列表中查找元素,您可以使用很多函数:find、nth、search、position,……参见https://lispcookbook.github.io/cl-cookbook/data-structures.html#函数因为minPos返回一个索引,你可能想要nth index listor elt sequence index


推荐阅读