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

Gak*_*kuo 1 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 ) ))
Run Code Online (Sandbox Code Playgroud)

Rai*_*wig 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 ) ))
Run Code Online (Sandbox Code Playgroud)

代码仍然格式奇怪.改进:

(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)))
Run Code Online (Sandbox Code Playgroud)

首先你可以看到函数=没有正确的参数列表.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))
Run Code Online (Sandbox Code Playgroud)

内部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))
Run Code Online (Sandbox Code Playgroud)

现在内部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))
Run Code Online (Sandbox Code Playgroud)