简体   繁体   中英

Clojure order hash map by value using key name as tiebreaker

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, eg \\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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM