gpt4 book ai didi

scala:实现一个通用的递归 max 函数

转载 作者:行者123 更新时间:2023-12-04 20:44:08 36 4
gpt4 key购买 nike

我正在尝试将此 haskell max 函数实现移植到 Scala

maximum' :: (Ord a) => [a] -> a  
maximum' [] = error "maximum of empty list"
maximum' [x] = x
maximum' (x:xs) = max x (maximum' xs)

这是我的第一次尝试:
def max[T <: Ordered[T]](list: List[T]): T = list match {

case Nil => throw new Error("maximum of empty list")
case head :: Nil => head
case list => {
val maxTail = max(list.tail)
if (list.head > maxTail) list.head else maxTail
}
}


max(List[Int](3,4))

但我收到以下错误:
inferred type arguments [Int] do not conform to method max's type parameter bounds [T <: Ordered[T]]

我尝试订购,可比较等,结果类似......

知道缺少什么吗?

最佳答案

也许你想要 Ordering类型类?

def max[T: Ordering](list: List[T]): T = list match {
case Nil => throw new RuntimeException("maximum of empty list")
case head :: Nil => head
case list =>
val maxTail = max(list.tail)
if (implicitly[Ordering[T]].gt(list.head, maxTail)) list.head else maxTail
}

这毕竟是如何内置 max方法有效:
// From GenTraversableOnce
def max[A1 >: A](implicit ord: Ordering[A1]): A

如果你这样做,你可以清理很多东西:
def max[T](list: List[T])(implicit ord: Ordering[T]): T = list match {
case Nil => throw new RuntimeException("maximum of empty list")
case head :: Nil => head
case head :: tail => ord.max(head, max(tail))
}

或者,您可以将其设为尾递归以提高效率(因为编译器会对其进行优化):
def max[T](list: List[T])(implicit ord: Ordering[T]): T = {
if (list.isEmpty)
throw new RuntimeException("maximum of empty list")

@tailrec
def inner(list: List[T], currMax: T): T =
list match {
case Nil => currMax
case head :: tail => inner(tail, ord.max(head, currMax))
}
inner(list.tail, list.head)
}

另外,你应该扔 RuntimeException或者它的一个子类,而不是 Error .

关于scala:实现一个通用的递归 max 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12506791/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com