[英]Is there a Haskell equivalent of Scala's Iterable.maxBy?
Scala's Iterable has maxBy
: Scala的Iterable有maxBy
:
Finds the first element which yields the largest value measured by function
f
. 找到产生函数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? 什么是等效的Haskell方法呢?
Scala's Iterable
is related to Haskell's Traversable
. Scala的Iterable
与Haskell的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
): 然而,在这种情况下, Foldable
就足以找到最大一个给定的集合,所以使用maximumBy
从Data.Foldable
会同compare `on` f
( on
从Data.Function
)或comparing f
( comparing
来自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
. 使用Data.List.maximumBy
和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.