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 quote
as 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?
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:
eval
) and some arguments.(+ 3 4)
list).eval
function with the list (+ 3 4)
as argument.eval
function does the same steps again, finding the normal function +
and the arguments, and applies it, obtaining the result.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With