Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 286
VincentDM Avatar asked Dec 20 '25 19:12

VincentDM


1 Answers

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.

like image 69
VincentDM Avatar answered Dec 22 '25 22:12

VincentDM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!