斯卡拉的Iterable有 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
例子:
scala> Seq(-2, 1).maxBy(Math.abs)
res0: Int = -2
scala> Seq(-2, 3).maxBy(Math.abs)
res1: Int = 3
等效的 Haskell 方法是什么?
最佳答案
斯卡拉的Iterable
与 Haskell 的 Traversable
相关.但是,在这种情况下,Foldable
足以找到给定集合的最大值,所以使用 maximumBy
from 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
关于scala - 有没有等效于 Scala 的 Iterable.maxBy 的 Haskell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25236258/