sorted-map返回现有键的nil值 [英] sorted-map returns nil value for existing key
问题描述
我尝试从排序的映射中按键获取值,并按比较器的值返回 nil
。
I try to get value by key from sorted map with comparator by value it returns nil
.
(def tmap {1 {:v 1} 2 {:v 2} 3 {:v 3}})
(def tmap-sorted
(apply sorted-map-by
#(let [val-comp (- (compare
(get-in tmap [%1 :v])
(get-in tmap [%2 :v])))]
(if (= val-comp 0)
1
val-comp))
(flatten (vec tmap))))
; => {3 {:v 3} 2 {:v 2} 1 {:v 1}}
(get tmap-sorted 3)
;=> nil
预期: {:v 3}
实际值: nil
推荐答案
您正在创建自定义比较器与 比较
用于 PersistentTreeMap
( tmap-sorted
的类型)来查找值,但是比较器从不返回0,这意味着两个对象相等。
You are creating a custom Comparator with compare
that is being used in PersistentTreeMap
(the type of tmap-sorted
) to lookup the value but your comparator never returns 0 which would mean that two objects are equal.
https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
在使用比较器时,应谨慎操作,该比较器能够施加与等于对排序的集合(或排序的映射图)进行排序的等于不一致的排序。假设将带有显式比较器c的排序集合(或排序映射)与从集合S提取的元素(或键)一起使用。如果c对S施加的排序与等式不一致,则排序集合(或排序映射)将表现奇怪。特别是,排序后的集合(或排序后的地图)将违反以等式定义的集合(或地图)的一般合同。
Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.
如果将比较器修改为 println
进行调试,则可以看到将 3 与 3 进行比较 1 表示它们不相等。
If you modify your comparator to println
for debug you can see that when compare 3 to 3 you get 1 meaning they are not equal.
(def tmap {1 {:v 1} 2 {:v 2} 3 {:v 3}})
(def tmap-sorted (apply
sorted-map-by
#(let [val-comp
(- (compare
(get-in tmap [%1 :v])
(get-in tmap [%2 :v])))
ret (if (= val-comp 0)
1
val-comp)]
(println "%1: " %1 " %2: " %2 " ret=" ret)
ret)
(flatten (vec tmap))))
(get tmap-sorted 3)
;; %1: 3 %2: 2 ret= -1
;; %1: 3 %2: 3 ret= 1
(get tmap-sorted 1)
;; %1: 1 %2: 2 ret= 1
;; %1: 1 %2: 1 ret= 1
所以您需要修复比较
函数以实现平等
So you need to fix your compare
function to work for equality
这篇关于sorted-map返回现有键的nil值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!