ClojureScript zipmap欺骗了我还是什么? [英] ClojureScript zipmap tricks me or what?
问题描述
我使用Clojurescript开发网络浏览器游戏。 (实际上,我的一个朋友教我,我们是在几周前才开始的)。
I use Clojurescript to develop webbrowser-games. (Actually a friend of mine teaches me, we started only a few weeks ago).
我想生成一个映射,其中键是向量,值是数字。例如:{[0 0] 0,[0 1] 1,[0 2] 2,...}。
I wanted to generate a map in which keys are vectors and values are numbers. For e.g.: {[0 0] 0, [0 1] 1, [0 2] 2, ...}.
我使用了以下公式:
(defn oxo [x y]
(zipmap (map vec (combi/cartesian-product (range 0 x) (range 0 y))) (range (* x y))))
(其中combi /表示clojure。
(where combi/ refers to clojure.math.combinatorics).
生成地图时,键值对是可以的,但它们是随机的,例如:
When it generates the map, key-value pairs are ok, but they are in a random order, like:
{[0 1] 1,[6 8] 68,[6 9] 69,[5 7] 57,...}
{[0 1] 1, [6 8] 68, [6 9] 69, [5 7] 57, ...}
使用zipmap后出了什么问题以及如何解决?
What went wrong after using zipmap and how can i fix it?
推荐答案
Clojure映射不保证已订购/排序键。如果要确保键已排序,请使用 sorted-map
:
Clojure maps aren't guaranteed to have ordered/sorted keys. If you want to ensure the keys are sorted, use a sorted-map
:
(into (sorted-map) (oxo 10 10))
=>
{[0 0] 0,
[0 1] 1,
[0 2] 2,
[0 3] 3,
[0 4] 4,
[0 5] 5,
...
如果您的地图少于9个键,则保留插入顺序,因为基础数据结构根据键的数量而有所不同:
If your map has fewer than 9 keys then insertion order is preserved because the underlying data structure is different depending on the number of keys:
-
clojure.lang.PersistentArrayMap
<9个键 -
clojure.lang.PersistentHashMap
否则。
clojure.lang.PersistentArrayMap
for <9 keysclojure.lang.PersistentHashMap
otherwise.
array-map
产生 clojure.lang.PersistentArrayMap
和 sorted-map
产生 clojure.lang.PersistentTreeMap
。请注意,将 assoc
插入数组映射可能会生成 hash 映射,但是 assoc
ing进入已排序的地图仍会生成已排序的地图。
array-map
produces a clojure.lang.PersistentArrayMap
and sorted-map
produces a clojure.lang.PersistentTreeMap
. Note that assoc
ing onto an array map may produce a hash map, but assoc
ing on to a sorted map still produces a sorted map.
这篇关于ClojureScript zipmap欺骗了我还是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!