3

Which of the following expressions has correct lisp syntax?

(+ 1 (quote 1))
==> 1 (???)
(+ 1 (eval (quote 1))
==> 2

I'm currently writing my own lisp interpreter and not quite sure how to handle the quotes correct. Most lisp interpreters I've had a look at evaluate both expressions to "2". But shouldn't the quote be not evaluated at all and thereby only the second one be a legal expression? Why does it work then anyway? Is this some kind of syntactical sugar?

yeahiii
  • 53
  • 1
  • 5
  • 2
    A good related question is [What is the difference between 1 and '1 in Lisp?](http://stackoverflow.com/questions/2966765/what-is-the-difference-between-1-and-1-in-lisp). – Peteris Sep 30 '11 at 12:08

2 Answers2

5

Barring special forms, most Lisps evaluate the arguments first, then apply the function (hence the eval-and-apply phrase).

Your first form (+ 1 '1) would first evaluate its arguments 1 and '1. Constant numerics evaluate to themselves, and the quote evaluates to what it quotes, so you'd be left applying + to 1 and 1, yielding 2.

eval: (+ 1 (quote 1))
eval 1st arg:  1 ==> 1
eval 2nd arg: '1 ==> 1
apply: (+ 1 1) ==> 2

The second form is similar, the unquoted 1 will just go through eval once, yielding 1 again:

eval: (+ 1 (eval '1))
eval 1st arg: 1 ==> 1
eval 2nd arg: (eval '1)
  eval arg:    '1 ==> 1
  apply: (eval 1) ==> 1
apply: (+ 1 1) ==> 2
JB.
  • 40,344
  • 12
  • 79
  • 106
3

Numbers evaluate to themselves so (quote 1) is the same as 1.

Peteris
  • 3,548
  • 4
  • 28
  • 44