简体   繁体   English

为什么Clojure向量用于传递键值对?

[英]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. 作为Clojure的新手,矢量(类似数组)和地图(键值对)之间的区别最初对我来说似乎很清楚。

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. 但是,在很多情况下(例如“let”特殊形式和带有关键字参数的函数),矢量用于传递键值对。

The source code for let even includes a check to ensure that the vector contains an even number of elements. let的源代码甚至包括一个检查,以确保向量包含偶数个元素。

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? 任何人都可以解释为什么矢量似乎也是表达键和值对的首选工具?

The wonderful people at the Clojure IRC channel explained to me the primary reason: maps (hashes) are not ordered . Clojure IRC频道的精彩人物向我解释了主要原因: 地图(哈希)没有订购

For example, the let form allows back-references which could break if the order of the arguments is not stable: 例如,let表单允许反向引用,如果参数的顺序不稳定,则可能会中断:

(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). vanilla Clojure没有有序的地图,除了按排序键排序的地图(这很奇怪)。

Thus, the need to keep arguments in order trumps the fact that they are key-value pairs. 因此,需要保持参数的顺序胜过它们是键值对的事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM