Can somebody explain why the function eval behaves like this?
(eval (list 'cons t n开发者_如何学Cil)) returns (T)
(eval (list 'cons 'a nil)) causes an error
(eval (list 'cons ''a nil)) returns (A)
Thanks a lot.
First:
(CONS T NIL)
T is a constant and returns T when evaluated. NIL is also a constant and evaluates to NIL. (CONS T NIL) then returns (T . NIL), which is shorter written as (T).
Second:
(CONS A NIL)
A is a variable. It is possibly undefined. Evaluating it will lead to an error when A is undefined.
Third:
Now you should think about the third form...
One more thing that you may want to note is that third form is embedding the symbol A in the list. Usually this is the form which is mostly taught in Lisp books for learning by experimenting on REPL. However in actual programs / functions, you may be using initially more of putting value or list represented by A in the list and not the symbol A.
e.g. (setf a 2)
(eval (list 'cons a nil)) => (2) [A is evaluated before list is evaluated; (eval '(cons 2 nil))]
(eval (list 'cons 'a nil)) => (2) [A is evaluated when (eval '(cons a nil)) is evaluated]
(eval (list 'cons ''a nil)) => (A) [A does not get evaluated as call is (eval '(cons 'a nil)); 'a is symbol A]
If you don't do (setf a 2) in the beginning, 1st and 2nd both forms will give error. This is because when a is evaluated, it is not bounded (i.e. crudely, it does not have any value associated with it)
精彩评论