Chris Martin
Chris Martin

Reputation: 30756

What is Clojure's equivalent of Scala's maxBy function?

Scala's TraversableOnce has maxBy:

maxBy[B](f: (A) ⇒ B)(implicit cmp: Ordering[B]): A

Finds the first element which yields the largest value measured by function f.

Does Clojure have something similar?

Upvotes: 1

Views: 119

Answers (1)

Chris Martin
Chris Martin

Reputation: 30756

The closest thing seems to be max-key:

(max-key k x) (max-key k x y) (max-key k x y & more)

Returns the x for which (k x), a number, is greatest.

The name makes it sound like it only works with maps, but k can be any function.

The only thing missing is that k must return a number, whereas Scala's can handle anything with an Ordering instance.

Upvotes: 5

Related Questions