我在使用带有 sorted-map-by 和 apply 的自定义比较器时遇到问题。如何使下面的表达式起作用-
(apply sorted-map-by > {1 "ab" 3 "cs" 2 "vs"})
我得到以下异常 -
IllegalArgumentException 没有为键提供值:[3 "cs"] clojure.lang.PersistentTreeMap.create (PersistentTreeMap.java:87)
我在使用带有 sorted-map-by 和 apply 的自定义比较器时遇到问题。如何使下面的表达式起作用-
(apply sorted-map-by > {1 "ab" 3 "cs" 2 "vs"})
我得到以下异常 -
IllegalArgumentException 没有为键提供值:[3 "cs"] clojure.lang.PersistentTreeMap.create (PersistentTreeMap.java:87)
Assuming you are wanting to sort on keys with an existing map, you could use into
:
(into (sorted-map-by >) {1 "ab" 3 "cs" 2 "vs"})
This works because (sorted-map-by >)
returns an empty sorted map, so using functions like into
and assoc
will work as expected while the map maintains the sorted order.
;=> {3 "cs", 2 "vs", 1 "ab"}
The sorted-map-by
function works on flat arguments:
(sorted-map-by > 1 "ab" 3 "cs" 2 "vs")
;=> {3 "cs", 2 "vs", 1 "ab"}
Applying it to this map would give an odd number of pairs:
(apply list {1 "ab" 3 "cs" 2 "vs"})
;=> ([1 "ab"] [2 "vs"] [3 "cs"])
And it is trying to make every other one a value to a preceding key, hence the error.
apply
如果在编译时不知道要传递给函数的参数数量,您将使用. 所以最好的方法是使用
(into (sorted-map-by >) {1 "ab" 3 "cs" 2 "vs"})