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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With