如何做最大的在clojure? [英] how to do max-by in clojure?

查看:98
本文介绍了如何做最大的在clojure?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个由(defrecord Person [name age])定义的记录序列,并且我想获得最大年龄的人的记录,

If I've got a sequence of records defined by (defrecord Person [name age]) and I want to get the record of the person with the maximum age, is there an easier way to do this than

(reduce #(if (> (:age %1) (:age %2)) %1 %2) people)

这是我想出的唯一方法到目前为止,但似乎这是一个常见的足够的情况下,必须有一些内置的库函数,使这更容易和/或更通用。

That's the only way I've figured out to do it so far, but it seems like this has to be a common enough scenario that there must be some built-in library functions that make this easier and/or more generic.

推荐答案

clojure.core / max-key 是一个合适的工作工具。

clojure.core/max-key is a suitable tool for the job.

 (apply max-key :age [{:age 12} {:age 20} {:age 30}]) ;; -> {:age 30}

这篇关于如何做最大的在clojure?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆