[英]In Clojure, how do I sort a set of maps by a key within a value?
This is an awkward question to phrase, but say I have a set of maps like so: 这对短语来说是一个尴尬的问题,但请说我有一组这样的地图:
(def person-1 {:name "Joshua" :birthday {:day 5 :month 12 :year 1960}})
(def person-2 {:name "Louise" :birthday {:day 17 :month 4 :year 1987}})
(def person-3 {:name "Jessica" :birthday {:day 28 :month 5 :year 1972}})
(def people #{person-1 person-2 person-3})
How would I sort people
by their birth month, for example? 例如,我将如何按
people
的出生月份对他们进行分类?
I know that I could just do (sort-by :name people)
if I wanted to sort by name, but I'm not sure, syntactically, how the example above would work. 我知道如果我想按名称
(sort-by :name people)
,我可以做(sort-by :name people)
,但是从语法上我不确定上面的示例如何工作。
Try: 尝试:
(sort-by (comp :year :birthday) people)
this sorts on the person's year of birth. 这取决于该人的出生年份。
comp
takes a list of functions and composes them into a single function that first takes the parameter, runs the function on the right first, takes the result and then proceeds leftward. comp
接受一个函数列表,并将它们组合成一个函数,该函数首先获取参数,首先在右侧运行该函数,获取结果,然后向左进行。
See comp
in ClojureDocs for details. 有关详细信息,请
comp
ClojureDocs中的comp
。
sort-by接受一个函数作为它的第一个参数,因此您可以执行以下操作:
(sort-by (fn [m] (-> m :birthday :month)) people)
Another option is to use an anonymous function: 另一种选择是使用匿名函数:
(sort-by #(:year (:birthday %)) people)
Share and enjoy. 分享并享受。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.