在循环中从使用 `with` 定义的变量调用 lambda 函数

问题描述 投票:0回答:2

我有以下 lisp 代码

(defun sum (vec)
  "Summiert alle Elemente eines Vektors."
  (apply '+ vec))

(defun square (item)
  "Hilfsfunktion zum Quadrieren eines Elements."
  (* item item))

(defun calcVarianz (vec)
  "Berechnet die Varianz eines Vektors."
  (loop with len = (length vec)
        with mean = (/ (sum vec) len)
        with some_func = (lambda (x) (* x x))
        ; causes the error
        for item in vec
        collecting (square (- item mean)) into squared
        collecting (some_func item) into some_vector
        ; some_func cannot be found
        finally (return (/ (sum squared) (- len 1)))))

效果很好(计算向量的方差)。
现在,我想知道是否可以将

sum
square
函数定义为
loop
构造中的 lambda,但一路上陷入困境。例如,这可能吗

with sum = (lambda (x) ...)

出现错误

The function COMMON-LISP-USER::SOME_FUNC is undefined.
   [Condition of type UNDEFINED-FUNCTION]

我在这里缺少什么?

lisp common-lisp
2个回答
4
投票

如果将符号绑定到函数,则在尝试使用符号调用函数时需要使用

funcall
apply

collecting (funcall some_func item) into some_vector

这是因为通常在绑定符号时会绑定value槽,而在这种情况下,值槽与函数的值绑定。当遇到一个符号作为 cons 的第一个元素时,将检查 function 槽是否有该函数,这是一个不同的命名空间。这就是为什么需要

funcall
(或
apply
):它们将符号的普通值强制为 功能 值。


2
投票

您可以使用

apply
,替换

collecting (some_func item) into some_vector

collecting (apply some_func (list item)) into some_vector
© www.soinside.com 2019 - 2024. All rights reserved.