Reputation: 1382
I am just starting to learn lisp and am a bit puzzled as to why the compiler does not evaluate a simple integer enclosed in parentheses to the value of that integer.
In the REPL, when I do (+ 3 2)
I get 5
, but when I do (+ 3 (2))
I get an error, whereas I think the value of the expression (2)
should also be 2
. Clearly there is something important here that I am unable to lay my finger on - what's the difference between 2
and (2)
? Any help would be most appreciated since this seems fundamental to the way lisp works.
Upvotes: 1
Views: 161
Reputation: 14905
You should also note that there is a difference between a list, and an form. All forms (+ 1 2)
are lists, but not all lists (2)
are forms.
When you type something at the prompt, that needs to be a form. The first part of a form almost always needs to be some kind of operator.
If you have the REPL prompt, and you type in the following, you will get an error, because it is just a list, not a form:
(2)
What will work is something that tells the REPL to construct a list:
'(2)
'(aardvark)
...which is really just shorthand for:
(quote (2))
(quote (aardvark))
Which means that it actually is still a list that starts with an operator, and is therefore a form.
The following examples will return results:
(+ 1 2)
(+ 1 (+ 2 3))
Basically, the way to think about it is that each element (except the first) in the list is evaluated, then the first element is executed on those elements. So (+ 1 (+ 2 3))
is first evaluated as 1
which results in 1, and then (+ 2 3)
which again first has the arguments evaluated before the operator is executed, which means 2 and 3 is fed to +, which results in 5, and then 1 and 5 is fed to +.
Is you say (+ 1 (2))
, it tries to evaluate each element after the first, going 1
evaluates to 1, but (2)
evaluates to... nothing, because the first element is not an operator.
By the way, I find it helpful to look at multiple books and sources, because if one states something in a way I don't understand, I can always consult another one to see if it makes more sense. I suggest these:
Hope that helps!
Upvotes: 1
Reputation: 139411
The supported Common Lisp syntax for list forms is specified here: CLHS Section 3.1.2.1.2 Conses as Forms.
There are four supported types of lists as forms:
(quote foo)
(defun foo (a1 a1) (+ a1 a2))
(+ 1 2)
((lambda (a) (+ a 1)) 2)
That's all. Other lists can't be evaluated in Common Lisp.
Upvotes: 3