Reputation: 1118
On "Programming Clojure", there is an example using get function on a vector:
(get [:a :b :c] 1)
-> :b
I called (doc get) and it looks like get function takes hashmap as argument but not vector, so I wander if vector is some kind of hashmap. I remember a hashmap can take an index integer, and return value matching that index, so I did this to see if vector can do same thing:
([1 2 3 4] 1)
-> 2
It did return value 2, which is at index 1 in [1 2 3 4].
Does this mean a vector is a hashmap, whose keys-value pair is index-value pair?
Upvotes: 6
Views: 271
Reputation: 84331
No, the underlying implementation is different.
That being said, since logically vectors do map indices to elements, they are associative structures in Clojure and can be used with get
, contains?
and assoc
(though for assoc
only indices from 0 to 1 past the end of the vector can be used). They cannot be used with dissoc
though -- that's a "real map" operation.
Also, vectors act differently to maps when used as functions: calling a map as a function is equivalent to using it with get
, while calling a vector is equivalent to using nth
. The difference is that nth
throws an exception on index-out-of-bounds (as well as arguments which could not possibly be indices, such as negative numbers or non-numbers), whereas get
returns nil
.
Upvotes: 8