VincentDM
VincentDM

Reputation: 113

Why are Clojure vectors used to pass key-value pairs?

As a newcomer to Clojure, the distinction between a vector (array-like) and a map (key-value pairs) initially seemed clear to me.

However, in a lot of situations (such as the "let" special form and functions with keyword arguments) a vector is used to pass key-value pairs.

The source code for let even includes a check to ensure that the vector contains an even number of elements.

I really don't understand why vectors are used instead of maps. When I read about the collection types, I would expect maps to be the preferred way to store any information in key-value format.

Can anyone explain me why vectors also seem to be the preferred tool to express pairs of keys and values?

Upvotes: 3

Views: 509

Answers (1)

VincentDM
VincentDM

Reputation: 113

The wonderful people at the Clojure IRC channel explained to me the primary reason: maps (hashes) are not ordered.

For example, the let form allows back-references which could break if the order of the arguments is not stable:

(let [a 1 b (inc a)] (+ a b))

The reason why ordered maps are not used

  1. they have no convenient literal
  2. vanilla Clojure has no ordered map except one that is ordered by sorting keys (which would be weird).

Thus, the need to keep arguments in order trumps the fact that they are key-value pairs.

Upvotes: 5

Related Questions