简体   繁体   中英

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

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM