Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Haskell equivalent of Scala's Iterable.maxBy?

Tags:

haskell

scala

Scala's Iterable has maxBy:

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

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

Example:

scala> Seq(-2, 1).maxBy(Math.abs)
res0: Int = -2

scala> Seq(-2, 3).maxBy(Math.abs)
res1: Int = 3

What's the equivalent Haskell way to do this?

like image 670
Chris Martin Avatar asked Aug 11 '14 05:08

Chris Martin


2 Answers

Scala's Iterable is related to Haskell's Traversable. However, in this case, Foldable is enough to find the maximum of a given collection, so use maximumBy from Data.Foldable in conjunction with compare `on` f (on from Data.Function) or comparing f (comparing from Data.Ord):

import Data.Foldable (maximumBy, Foldable)
import Data.Ord      (comparing)

maxBy :: (Foldable t, Ord a) => (b -> a) -> t b -> b
maxBy = maximumBy . comparing
like image 144
Zeta Avatar answered Oct 16 '22 10:10

Zeta


Use Data.List.maximumBy and Data.Ord.comparing.

comparing :: Ord a => (b -> a) -> b -> b -> Ordering

maximumBy :: (a -> a -> Ordering) -> [a] -> a

Example:

> import Data.Ord (comparing)
> import Data.List (maximumBy)

> maximumBy (comparing abs) [-2, 1]
-2

> maximumBy (comparing abs) [-2, 3]
3
like image 8
Chris Martin Avatar answered Oct 16 '22 12:10

Chris Martin