Clojure:如何在交换前将哈希映射转换到前面!功能 [英] Clojure: how to conj to front of hash map in swap! function

查看:94
本文介绍了Clojure:如何在交换前将哈希映射转换到前面!功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了它将新值添加到哈希映射的 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). conjing 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 on index, where old-key is whatever keys you're using now.

这篇关于Clojure:如何在交换前将哈希映射转换到前面!功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆