Search code examples
elisp

Return a function as argument in SICP example average-damp


I tried the following higher-order function from SICP:

(defun average-damp(f)
  (lambda (x) (average x (f x))))
(defun average(x y)
     (/ (+ x y) 2.0))
(defun square(x)
  (* x x))
((average-damp square) 10)

Namely, given a function f, we consider the function whose value at x is equal to the average of x and f(x).

But running it reports an error:

progn: Invalid function: (average-damp square)

I verified that square and average work correctly. Here's the original version average-damp in Scheme:

(define (average-damp f)
  (lambda (x) (average x (f x))))

What's the problem?


Solution

  • You seem to be looking for apply or funcall. They have similar functionality but accept their arguments differently.

    (funcall (average-damp square) 10)
    

    See also https://www.gnu.org/software/emacs/manual/html_node/elisp/Calling-Functions.html