CL - 如何将obj参数传递给标签函数?

时间:2012-10-18 15:22:29

标签: lisp

(defparameter *objects* '(whiskey bucket frog chain))

(defparameter *object-locations* '((whiskey living-room)
                                   (bucket living-room)
                                   (chain garden)
                                   (frog garden)))

(defun objects-at (loc objs obj-locs)
  (labels ((at-loc-p (obj)
             (eq (cadr (assoc obj obj-locs)) loc)))
    (remove-if-not #'at-loc-p objs)))

(objects-at 'living-room *objects* *object-locations*)

在REPL中返回(WHISKEY BUCKET)

obj如何传递到at-loc-pobjects-at的所有参数均未命名为obj

2 个答案:

答案 0 :(得分:1)

objects-at的所有参数均未命名为obj,但at-loc-p的参数之一(实际上是唯一参数)是。{1}}。因此,当使用参数(at-loc-p)调用remove-if-not时,该参数将传递给名为at-loc-p的{​​{1}}。

答案 1 :(得分:0)

labels定义了函数。所以

(labels ((square (x) (* x x))) (square 2))

相同
(let ((square (lambda (x) (* x x)))) (funcall square 2))

x(在您的示例中,obj)只是squareat-loc-p)函数的参数名称。

编写函数objects-at的另一种方法是

(defun objects-at (loc objs obj-locs)
  (defun at-loc-p (obj)
    (eq (cadr (assoc obj obj-locs)) loc))
  (remove-if-not #'at-loc-p objs)))

除了全局定义函数at-loc-p