sorted-map-by

added
1.0

ns
clojure.core

type
function

(sorted-map-by comparator & keyvals)

keyval => key val
Returns a new sorted map with supplied mappings, using the supplied
comparator.  If any keys are equal, they are handled as if by
repeated uses of assoc.

                ; The basic function requires discrete elements, and cannot accept a 
; pre-existing map:
user=> (sorted-map-by > 1 "a", 2 "b", 3 "c")
{3 "c", 2 "b", 1 "a"}

; We can use the syntax "(sorted-map >)" to create an empty sorted map that sorts 
; in reverse order (i.e. the opposite of "(sorted-map)").  It we can then fill
; it using (into ...) with a pre-existing map:
user=> (into (sorted-map-by >)  {1 :a  2 :b  3 :c} )
{3 :c, 2 :b, 1 :a}

; This two are the same
user=> (into (sorted-map-by <)  {1 :a  2 :b  3 :c} )
{1 :a, 2 :b, 3 :c}
user=> (into (sorted-map)  {1 :a  2 :b  3 :c} )
{1 :a, 2 :b, 3 :c}


            
                ;; If you wish to sort the map according to the values, instead of by keys 
;; the following code WILL NOT WORK! This is because the map values are not unique.

user=> (let [results {:A 1 :B 2 :C 2 :D 5 :E 1 :F 1}]
  (into (sorted-map-by (fn [key1 key2]
                         (compare (get results key2)
                                  (get results key1))))
        results))

=> {:D 5, :C 2, :A 1}

;; To make sure that the sorting works, we can make sure that the comparator 
;; works on unique values

user=> (let [results {:A 1 :B 2 :C 2 :D 5 :E 1 :F 1}]
  (into (sorted-map-by (fn [key1 key2]
                         (compare [(get results key2) key2]
                                  [(get results key1) key1])))
        results))

=> {:D 5, :C 2, :B 2, :F 1, :E 1, :A 1}