4

This is related to this question: elisp functions as parameters and as return value

(defun avg-damp (n)
   '(lambda(x) (/ n 2.0)))

Either

(funcall (avg-damp 6) 10)

or

((avg-damp 6) 10)

They gave errors of Symbol's value as variable is void: n and eval: Invalid function: (avg-damp 6) respectively.

Community
  • 1
  • 1
RNA
  • 146,987
  • 15
  • 52
  • 70
  • 1
    Please don't quote your lambdas. Other than that, your example will work in a recent Emacs, provided you do it in a buffer where you've set `lexical-binding` to `t`. – Stefan May 04 '13 at 23:22

1 Answers1

8

The reason the first form does not work is that n is bound dynamically, not lexically:

(defun avg-damp (n)
  (lexical-let ((n n))
    (lambda(x) (/ x n))))
(funcall (avg-damp 3) 12)
==> 4

The reason the second form does not work is that Emacs Lisp is, like Common Lisp, a "lisp-2", not a "lisp-1"

Community
  • 1
  • 1
sds
  • 58,617
  • 29
  • 161
  • 278
  • 2
    Just a note: The distinction between a lisp-1 and a lisp-2 is whether symbols have just a value binding (a lisp-1) or a value binding and a function binding. A lisp-2 could still have an evaluation semantics that says "to evaluate (f a1 a2 …), if f is a symbol, apply its function binding to a1 a2 …, else if f is a compound form, evaluate it and apply the result to a1 a2 …". In Common Lisp we can already do ((lambda (x) (list x x)) 4) and get (4 4). I think a lisp that supports ((…) …) could still be a lisp-2, so long as (f …) only applies f's function binding, not is value binding. – Joshua Taylor May 02 '13 at 19:35
  • 3
    @JoshuaTaylor `((lambda (...)...) ...)` is a special case in Cl. Typically, you are getting the value "binding" (well, value) whenever you evaluate a function, but `(lambda (...) ...)` *only* has a function "value" rather than a general value, so it's been explicitly allowed. – Vatine May 03 '13 at 11:43
  • @Vatine Absolutely right. Had not CL that special case, we'd `(let ((f (lambda (…) …))) (apply f …))` just as we do for non-`lambda` forms. My point, though, was that non-symbol, function-producing forms in function position doesn't fundamentally require any modification to separate function and value namespaces. (In CL, other things (e.g., symbol macros) might cause issues.) If some lisp allowed non-symbol, function-producing forms in function position, and has separate function and value namespaces, I'd be more inclined to call it a lisp-2 than a lisp-1. – Joshua Taylor May 03 '13 at 13:00
  • Is there a way to invoke this function without funcall : for example (#'(avg-dump 5) 10). I could not find any other way than a funcall. which looks kind of ugly. – yilmazhuseyin May 03 '13 at 14:26
  • 1
    @yilmazhuseyin: no. you will have to use either `funcall` or `apply`. – sds May 03 '13 at 14:33