使用局部变量并在嵌套的Common Lisp循环中返回它们

时间:2018-05-31 17:51:15

标签: common-lisp nested-loops

我有以下代码,嵌套循环有问题: 我的目标是为学术目的实施CLOS多调度(多方法)。我有一个传递给泛型函数的参数列表。泛型函数(gf)包含方法列表。反过来,泛型函数中的每个方法都包含它所操作的参数所属的类(特化器)列表。对于适用的方法,传递给泛型函数的每个参数必须是泛型函数的方法列表中包含的方法中其各自的特化器的实例或子类。特别是,使用局部变量并在嵌套循环中返回它们是一个问题。

(defun compute-applicable-methods (gf &rest args)
     (loop for method in (generic-function-methods gf)
                    do (loop for specializer in (method-specializer method)
                              for arg in args
                               counting (instancep arg specializer) into matched_args
                                  )
         when (= matched_args (count args)
        collect method ) ))

1 个答案:

答案 0 :(得分:6)

如果没有适当的缩进和代码格式,您应该不编写代码,也不编写任何Lisp代码。使用Lisp你也没有任何借口,因为IDE会为你缩进代码。

缩进修正:

(defun compute-applicable-methods (gf &rest args)
  (loop for method in (generic-function-methods gf)
        do (loop for specializer in (method-specializer method)
                 for arg in args
                 counting (instancep arg specializer) into matched_args
                 )
        when (= matched_args (count args)
                collect method ) ))

代码仍然是奇怪的格式。改进:

(defun compute-applicable-methods (gf &rest args)
  (loop for method in (generic-function-methods gf)
        do (loop for specializer in (method-specializer method)
                 for arg in args
                 counting (instancep arg specializer) into matched_args)
        when (= matched_args (count args)
                collect method)))

首先你可以看到函数=没有正确的参数列表。 collectmethod不应该是=的参数:

(defun compute-applicable-methods (gf &rest args)
  (loop for method in (generic-function-methods gf)
        do (loop for specializer in (method-specializer method)
                 for arg in args
                 counting (instancep arg specializer) into matched-args)
        when (= matched-args (count args))
        collect method))

内部LOOP不会返回任何值,您会计入一个您不会使用的本地变量matched-args

如果您不使用该变量,请将其删除:

(defun compute-applicable-methods (gf &rest args)
  (loop for method in (generic-function-methods gf)
        do (loop for specializer in (method-specializer method)
                 for arg in args
                 count (instancep arg specializer))
        when (= matched-args (count args))
        collect method))

现在内部LOOP会返回一个值,但我们不会使用它。改进:

(defun compute-applicable-methods (gf &rest args)
  (loop for method in (generic-function-methods gf)
        for matched-args = (loop for specializer in (method-specializer method)
                                 for arg in args
                                 counting (instancep arg specializer))
        when (= matched-args (count args))
        collect method))