yeahiii
yeahiii

Reputation: 53

Lisp: Evaluation of quotes

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?

Upvotes: 3

Views: 1323

Answers (2)

Peteris
Peteris

Reputation: 3756

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

Upvotes: 3

JB.
JB.

Reputation: 42114

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

Upvotes: 5

Related Questions