Quoting in clojure results in non-evaluation. ':a
and :a
return the same result. What is the difference between 开发者_C百科':a and :a ? One is not evaluated and other evaluates to itself... but is this same as non-evaluation ?
':a
is shorthand for(quote :a)
.(eval '(quote form))
returnsform
by definition. That is to say, if the Clojure functioneval
receives as its argument a list structure whose first element is the symbolquote
, it returns the second element of said list structure without transforming it in any way (thus it is said that the quoted form is not evaluated). In other words, the behavioureval
dispatches to when its argument is a list structure of the form(quote foo)
is that of returningfoo
unchanged, regardless of what it is.When you write down the literal
:a
in your programme, it gets read in as the keyword:a
; that is, the concrete piece of text:a
gets converted to an in-memory data structure which happens to be called the:a
keyword (Lisp being homoiconic means that occasionally it is hard to distinguish between the textual representation of Lisp data and the data itself, even when this would be useful for explanatory purposes...).The in-memory data structure corresponding to the literal
:a
is a Java object which exposes a number of methods etc. and which has the interesting property that the functioneval
, when it receives this data object as an argument, returns it unchanged. In other words, the keyword's "evaluation to itself" which you ask about is just the behavioureval
dispatches to when passed in a keyword as an argument.Thus when
eval
sees':a
, it treats it as a quoted form and returns the second part thereof, which happens to be:a
. When, on the other hand,eval
sees:a
, it treats it as a keyword and returns it unchanged. The return value is the same in both cases (it's just the keyword:a
); the evaluation process is slightly different.Clojure semantics -- indeed Lisp semantics, for any dialect of Lisp -- are specified in terms of the values returned by and side-effects caused by the function
eval
when it receives various Lisp data structures as arguments. Thus the above explains what's actually meant to happen when you write down':a
or:a
in your programme (code like(println :a)
may get compiled into efficient bytecode which doesn't actually code the functioneval
, of course; but the semantics are always preserved, so that it still acts as if it waseval
receiving a list structure containing the symbolprintln
and the keyword:a
).The key idea here is that regardless of whether the form being evaluated is
':a
or:a
, the keyword data structure is constructed at read time; then when one of these forms is evaluated, that data structure is returned unchanged -- although for different reasons.
精彩评论