Search code examples
lispcommon-lisp

Calling a lambda function in a loop from a variable defined with `with`


I have the following lisp code

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

which works great (calculates the variance of a vector, that is).
Now, I was wondering if one could define the sum and the square functions as lambda within the loop construct but got stuck along the way. Is this possible with e.g.

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

Got the error

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

What am I missing here?


Solution

  • You could use apply, replacing

    collecting (some_func item) into some_vector
    

    with

    collecting (apply some_func (list item)) into some_vector