Domanda

actually i am trying to perfectly understand clojure and particularly symbols

(def a 1)
(type a)
;;=>java.lang.Long
(type 'a)
;;=>clojure.lang.Symbol

I know that type is a function so its arguments get evaluated first so i perfectly understand why the code above work this way .In the flowing code i decided to delay the evaluation using macro

 (defmacro m-type [x] (type x))
 (m-type a)
 ;;==>clojure.lang.Symbol

and i am fine with that but what i fail to uderstand is this:

 (m-type 'a)
 ;;=>clojure.lang.Cons

why the type of 'a is a cons

È stato utile?

Soluzione

the character ' is interpreted by the clojure reader as a reader-macro which expands to a list containing the symbol quote followed by whatever follows the ', so in your call to (m-type 'a) the 'a is expanding to:

user> (macroexpand-1 ''a)
(quote a) 

then calling type on the list (quote a) which is a Cons.

This may be a bit more clear if we make the m-type macro print the arguments as it sees them while it is evaluating:

user> (defmacro m-type [x] (println "x is " x) (type x))
#'user/m-type
user> (m-type 'a)
x is  (quote a)
clojure.lang.Cons  
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top