Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Clojure allow (eval 3) although 3 is not quoted?

Tags:

clojure

eval

lisp

I'm learning Clojure and trying to understand reader, quoting, eval and homoiconicity by drawing parallels to Python's similar features.

In Python, one way to avoid (or postpone) evaluation is to wrap the expression between quotes, eg. '3 + 4'. You can evaluate this later using eval, eg. eval('3 + 4') yielding 7. (If you need to quote only Python values, you can use repr function instead of adding quotes manually.)

In Lisp you use quote or ' for quoting and eval for evaluating, eg. (eval '(+ 3 4)) yielding 7.

So in Python the "quoted" stuff is represented by a string, whereas in Lisp it's represented by a list which has quoteas first item.

My question, finally: why does Clojure allow (eval 3) although 3 is not quoted? Is it just the matter of Lisp style (trying to give an answer instead of error wherever possible) or are there some other reasons behind it? Is this behavior essential to Lisp or not?

like image 463
Aivar Avatar asked Dec 27 '12 00:12

Aivar


1 Answers

The short answer would be that numbers (and symbols, and strings, for example) evaluate to themselves. Quoting instruct lisp (the reader) to pass unevaluated whatever follows the quote. eval then gets that list as you wrote it, but without the quote, and then evaluates it (in the case of (eval '(+ 3 4)), eval will evaluate a function call (+) over two arguments).

What happens with that last expression is the following:

  1. When you hit enter, the expression is evaluated. It contain a normal function call (eval) and some arguments.
  2. The arguments are evaluated. The first argument contains a quote, which tells the reader to produce what is after the quote (the actual (+ 3 4) list).
  3. There are no more arguments, and the actual function call is evaluated. This means calling the eval function with the list (+ 3 4) as argument.
  4. The eval function does the same steps again, finding the normal function + and the arguments, and applies it, obtaining the result.
like image 130
Diego Sevilla Avatar answered Oct 03 '22 13:10

Diego Sevilla