## Sunday, March 22, 2015

### Vectors and Maps are Only Different in Your Mind

"That roars so loud and thunders in the index?"
-- Shakespeare, Hamlet

The other day I found something interesting while reading Clojure Programming.

"While it might be counterintuitive, maps and vectors are both associative collections, where vectors associate values with indices."
-- Clojure Programming, page 100

This is yet another case of the book, Clojure Programming, stating something that I thought of but was unable to adequately express in words.
The differences placed around data structures are often either just in our minds or a condition you place on the structure its self.

In the case of the structures just being different in our minds we can look at the example of a map and vector in Clojure.

We see in the example above that we could use a vector as a map where the indices are the keys.  We see in the first example (get v 1) that we are just using the index of 1 to get the second value from the vector (indices are zero based in Clojure).  With the second example (get v 99 :not-found) we see that we can assign a default value to be return when a value is not found.  In the last vector example we see that we can associate new values in the vector resulting in a different vector being returned (do not worry vectors are immutable in Clojure).  In the map examples we see we can treat a map like a vector by using integers for the keys.

In the second case of data structures being different due to a condition imposed on them, we do not have to look an further than our example of a map.

```
(assoc m

1 "Mr. Jack"

0 2002

2 :good-boy)

;; {0 2002, 1 "Mr. Jack", 3 4, 2 :good-boy}
```

We see a map is unordered in Clojure.  If you want to have the data be stored in an order then you would want to use a sorted-map instead of a hash-map.