Reputation: 1717
I'd like to be able to sort a hash-map by the value of it's keys, using the key name itself in the event of a tie
I have an an ordering function taken from the Clojure wiki https://clojuredocs.org/clojure.core/sorted-map-by#example-542692d5c026201cdc327094
(defn order-map [target]
(into (sorted-map-by (fn [key1 key2]
(compare [(target key2) key2]
[(target key1) key1]))) target))
Currently I'm able to do
(-> "notarealroom" frequencies order-map)
which outputs
{\o 3, \r 2, \a 2, \t 1, \n 1, \m 1, \l 1, \e 1}
but I'd like to be able to sort those keys with the same value, e.g. \r
and \a
alphabetically to give something like the following...
{\o 3, \a 2, \r 2, \e 1, \l 1, \m 1, \n 1, \t 1}
I'm unsure how to modify the compare function to deal with this tie-break scenario
Upvotes: 0
Views: 406
Reputation: 4513
You were almost there. The following should do the right thing:
(defn order-map [target]
(into (sorted-map-by (fn [key1 key2]
(compare [(target key2) key1]
[(target key1) key2]))) target))
Upvotes: 2