Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do max-by in clojure?

Tags:

clojure

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.

like image 496
lobsterism Avatar asked May 23 '13 08:05

lobsterism


2 Answers

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

 (apply max-key :age [{:age 12} {:age 20} {:age 30}]) ;; -> {:age 30}
like image 80
deprecated Avatar answered Nov 20 '22 22:11

deprecated


(last (sort-by :age [{:age 12} {:age 20} {:age 30}]))

sort-by uses compare

like image 41
noisesmith Avatar answered Nov 21 '22 00:11

noisesmith