Why do `vector` and` [...] `sometimes behave differently in Clojure?

In Clojure, square brackets are shorthand for defining vectors:

user=> (vector 'a 'b 'c) [abc] user=> ['a 'b 'c] [abc] 

The documentation page for vector talks about the long path and short path for defining vectors.

However, in defn and doseq there seems to be a difference.

 user=> (doseq [x (range 1 4)] (printf "%d\n" x)) 1 2 3 nil user=> (doseq (vector 'x (range 1 4)) (printf "%d\n" x)) IllegalArgumentException doseq requires a vector for its binding in user:1 clojure.core/doseq (core.clj:2935) 

What explains this difference? Are square brackets a special status in the reader, or do they have a specific shape in sugar?

+6
source share
1 answer

vector is evaluated after macro expansion, and [] is evaluated while reading before macros are expanded. In your second case, the doseq macro doseq not see the vector, it sees a list starting with the vector character, as the macros expand before regular functions are evaluated.

+9
source

All Articles