9

I was told that I shouldn't quote lambda in, say,

(global-set-key (quote [f3]) '(lambda ()   (interactive) (other-window -1) ))

I tried that indeed if I don't quote lambda, it works equally well

(global-set-key (quote [f3]) (lambda ()   (interactive) (other-window -1) ))

However, I don't understand why the latter works (and is also being preferred, and now that the latter works, why the former also works).

If the lambda expression is defined as an other function, we would have called

(global-set-key (quote [f3]) 'my-function)

to prevent my-function to be evaluated immediately. I understand the lambda expression as an anonymous version of my-function. So why shouldn't lambda be quoted?

Thanks!

Yi Wang
  • 515
  • 3
  • 12
  • 1
    Vector literals are also "self quoting", by the way, so there is no point quoting them either. – gsg Jan 06 '14 at 11:39
  • 2
    Not quite a duplicate, but see [When should Emacs #'function syntax be used?](http://stackoverflow.com/questions/16801396/when-should-emacs-function-syntax-be-used) – phils Jan 06 '14 at 21:44

1 Answers1

11

Using C-h f lambda <RET>:

A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is self-quoting; the result of evaluating the lambda expression is the expression itself.

So, this answers the question, why you don't need to quote the lambda expression. As to why you shouldn't do it... I think, this has to do with byte compilation. A quoted lambda expression is simply plain data. The byte code compiler has no choice but to include the expression as a constant list literal into its output. An unquoted lambda expression, on the other hand, can be compiled to byte code, resulting in faster execution.

List literals of the form (lambda (...) ...) are special-cased in emacs lisp evaluator and can be used as functions. That's why it works, regardless of whether you quote the lambda expression or not.

Dirk
  • 30,623
  • 8
  • 82
  • 102
  • 2
    And if you use `C-h f function RET` you get this: `Like 'quote', but preferred for objects which are functions. In byte compilation, 'function' causes its argument to be compiled. 'quote' cannot do that`. So, yes, it seems the problem with `quote` is that it avoids byte compilation. – rsenna Jan 06 '14 at 11:07
  • And be aware that other Lisps besides Emacs Lisp do not necessarily treat `lambda` forms this way. So you might see, for example, `#'(lambda...)` in other Lisp dialects. In Emacs Lisp this is treated essentially the same as `(lambda...)` (but as @Dirk pointed out, not the same as `'(lambda...)`). – Drew Jan 06 '14 at 18:07