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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With