要使用sort-by,您需要提供排序或您的优先级值。您可以实现自定义比较器来比较您的地图或为 sort-by 定义一个 keyfn 来计算用于排序的键。 keyfn 的解决方案如下。仅使用 keyfn 返回符合您要求的可比较值比实现比较器要容易得多。你可能想看看Comparators Guide。
我们开始定义一个函数来将字符串优先级转换为它的数字表示:
(let [priorities {"Medicore" 0
"Enormous" 1
"Weeny" 2}]
(defn priority->num [p]
(if-let [num (priorities p)]
num
(throw (IllegalArgumentException. (str "Unknown priority: " p))))))
(priority->num "Enormous")
;; => 1
现在我们需要计算每个地图的最大优先级:
(defn max-priority-num [m]
(->> m
(vals)
(map (comp priority->num :priority))
(apply max)))
(max-priority-num {:1 {:priority "Medicore" :somekey "SomeValue"}
:2 {:priority "Enormous" :somekey "SomeValue"}
:3 {:priority "Weeny" :somekey "SomeValue"}})
;; => 2
现在我们终于可以使用sort-by了:
(def m1 {:1 {:priority "Medicore" :somekey "SomeValue"}
:2 {:priority "Medicore" :somekey "SomeValue"}
:3 {:priority "Weeny" :somekey "SomeValue"}})
(def m2 {:1 {:priority "Medicore" :somekey "SomeValue"}
:2 {:priority "Enormous" :somekey "SomeValue"}
:3 {:priority "Weeny" :somekey "SomeValue"}})
(def m3 {:1 {:priority "Medicore" :somekey "SomeValue"}
:2 {:priority "Medicore" :somekey "SomeValue"}
:3 {:priority "Medicore" :somekey "SomeValue"}})
(sort-by max-priority-num [m1 m2 m3])
;; =>
({:1 {:priority "Medicore", :somekey "SomeValue"},
:2 {:priority "Medicore", :somekey "SomeValue"},
:3 {:priority "Medicore", :somekey "SomeValue"}}
{:1 {:priority "Medicore", :somekey "SomeValue"},
:2 {:priority "Medicore", :somekey "SomeValue"},
:3 {:priority "Weeny", :somekey "SomeValue"}}
{:1 {:priority "Medicore", :somekey "SomeValue"},
:2 {:priority "Enormous", :somekey "SomeValue"},
:3 {:priority "Weeny", :somekey "SomeValue"}})