Reputation: 47441
I am having trouble using a custom comparator with sorted-map-by and apply. How do I make the expression below work -
(apply sorted-map-by > {1 "ab" 3 "cs" 2 "vs"})
I get the below exception -
IllegalArgumentException No value supplied for key: [3 "cs"] clojure.lang.PersistentTreeMap.create (PersistentTreeMap.java:87)
Upvotes: 1
Views: 145
Reputation: 26446
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.
Upvotes: 5
Reputation: 32488
You would use apply
, if the number of arguments to pass to the function is not known at compile-time. So the best way is to use
(into (sorted-map-by >) {1 "ab" 3 "cs" 2 "vs"})
Upvotes: 1