是否在Clojure中订购地图? [英] Are maps in Clojure ordered?
问题描述
我来自Python,默认情况下,地图(即字典)不排序。开始学习Clojure时,我遇到了这个问题:
I'm coming from Python where maps (i.e. dicts) are not ordered by default. Starting to learn Clojure and I came across this:
(def point {:x 5 :y 7})
=> #'user/point
point
=> {:x 5, :y 7}
(let [{:keys [x y]} point]
(println "x:" x "y:" y))
x: 5 y: 7
在我看来,要使这种破坏有效,必须依靠地图排序(当然要记住顺序)。
It seems to me that for this destructuring to work one would have to rely on the map being ordered (and of course, remembering the order). Is that true?
推荐答案
Clojure映射没有排序,尽管存在诸如排序的问题-地图
。由于使用键访问值,因此获得一致的顺序。看看更改键名时会发生什么...
Clojure maps are not ordered, although there is a such thing as a sorted-map
. You are getting a consistent order because you are using the keys to access the values. See what happens when you change the key names...
user=> point
{:a 5, :b 7}
user=> (let [{:keys [x y]} point]
#_=> (println "x:" x "y:" y))
x: nil y: nil
nil
user=> (let [{:keys [a b]} point]
#_=> (println "a:" a "b:" b))
a: 5 b: 7
我有一个类似的问题,具有与您的问题相关的可接受的答案。
I had a similar question that has an accepted answer that is relevant to your question.
这篇关于是否在Clojure中订购地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!