Clojure:如何在交换前将哈希映射转换到前面!功能 [英] Clojure: how to conj to front of hash map in swap! function
问题描述
除了它将新值添加到哈希映射的 end ,此操作正常:
This works ok, except it adds the new value to the end of the hash map:
swap!my-atom conj @ new-fields)
我需要 my-atom
为@ new-fields中的第一个项目。我试过 assoc-in
, cons
几乎一切可能把事情一起。我可以做到在
? @ new-前面的
字段 my-atom
中交换
I need for my-atom
to be the first item in @new-fields. I have tried assoc-in
, cons
and pretty much everything that might "put things together". What can I do to swap!
in my-atom
to the front of @new-fields
?
推荐答案
散列映射是无序集合;在逻辑上,它们不具有开始或结束。它们有一个迭代顺序,它是一个实现细节(基于键的散列),用户不应该依赖它。此迭代顺序将在同一映射的读数之间一致,因为映射是不可变的值。
Hash-maps are unordered collections; logically they do not have a "beginning" or an "end". They have an iteration order, which is an implementation detail (based on the hashes of the keys) and which users should not rely upon. This iteration order will be consistent between readings of the same map because the map is an immutable value.
听起来你想要一个不同的数据类型,提供可预测的排序。 排序的地图是最简单的替换。您可以使用 sorted-map
(在键上使用比较
排序),或 map-by
(它使用比较器函数来比较键)。 conj
将一个键值对放入一个键,如果新键根据比较器最低,则将它放在第一位。
请注意,这些仍然是逻辑的maps:如果比较器说两个键相等,那么它们是相同的键,结果映射将只有一个值。
It sounds like you want a different datatype, to provide predictable ordering. Sorted maps are the easiest replacement. You can create them using sorted-map
(which sorts using compare
on the keys), or sorted-map-by
(which takes a comparator function to compare keys with). conj
ing a key-value pair into one will put it first iff the new key is lowest according to the comparator.
Note that these are still logical maps: If the comparator says two keys equal one another then they are the same key and the resulting map will only have one value for them.
如果你不能满足你的要求,听起来你并没有真正使用逻辑地图,因为这两个值都有索引和键。如果你真的需要手动设置顺序,有几种选择可能是
If you can't make that fit your requirements, it sounds like you're not actually using a logical map, since the values have both an index and a key. A few alternatives if you really need to manually set the order might be
- 一个向量
[键值]
元组或带有单个键/值对的映射。 - 在
索引上排序的组合键
[index old-key]
c>,其中old-key
是您现在使用的任何键。
- A vector of
[key value]
tuples or maps with a single key/value pair. - A map with composite keys
[index old-key]
, sorted onindex
, whereold-key
is whatever keys you're using now.
这篇关于Clojure:如何在交换前将哈希映射转换到前面!功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!