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

时间:2012-09-20 05:55:24

标签: scala generics recursion

我正在尝试将此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]]

我试着订购,比较等,结果相似......

有关缺少什么的想法吗?

9 个答案:

答案 0 :(得分:18)

通过与OP sans模式匹配和泛型类型相似的练习,并提出以下内容:

def max(xs: List[Int]): Int = {
    if (xs.isEmpty) throw new NoSuchElementException

    if (xs.length == 1) 
        return xs.head 
      else 
        return max(xs.head, max(xs.tail))
  }

  def max(x: Int, y: Int): Int = if (x > y) x else y

答案 1 :(得分:16)

也许你想要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

答案 2 :(得分:5)

我刚刚提出了这个解决方案。

def max(xs: List[Int]): Int = {
    if (xs.isEmpty) 0
    else {
      if( xs.head >= max(xs.tail) ) xs.head
      else max(xs.tail)
    }
}

答案 3 :(得分:1)

我提出了一个很容易理解的简单解决方案。它适用于空列表,只包含一个元素的列表和负数。

def max(xs: List[Int]): Int = {

  if (xs.isEmpty) throw new NoSuchElementException
  else {
    def inner(max: Int, list: List[Int]): Int = {

      def compare(x: Int, y: Int): Int =
        if (x > y) x
        else y

      if (list.isEmpty) max
      else inner(compare(max, list.head), list.tail)
    }
    inner(xs.head, xs.tail)
  } 
}

答案 4 :(得分:0)

哎呀,在询问之前看起来应该更好看

我在这个帖子中找到了答案:https://stackoverflow.com/a/691674/47633

似乎Haskell的类型类是使用scala中的implicits实现的(就像在dhg的例子中一样)

所以它最终会这样:

def max[T](list: List[T])(implicit f: T => Ordered[T]): T = {

 def maxElement(value1: T, value2: T): T = if (value1 > value2) value1 else value2

 list match {
    case Nil => throw new Error("empty list found")
    case head :: Nil => head
    case list => maxElement(list.head, max(list.tail))
  }
} 

或者用一些语法糖,只是

def max[T <% Ordered[T]](list: List[T]): T = list match {

尽管如此,我认为编译器有足够的信息可以自己完成......

ps:我有点喜欢这个功能...

答案 5 :(得分:0)

def genFunc[A](a1: A, a2: A)(f:(A, A) => Boolean):A = if (f(a1, a2)) a1 else a2
def min[A : Ordering] = (a1: A, a2: A) => implicitly[Ordering[A]].lt(a1, a2)
def max[A : Ordering] = (a1: A, a2: A) => implicitly[Ordering[A]].gt(a1, a2)

List(1,2,8,3,4,6,0).reduce(genFunc(_,_)(min))
List(1,2,8,3,4,6,0).reduce(genFunc(_,_)(max))

或者如果仅需要使用max函数进行尾递归并且Option [_]类型不会破坏参照透明性

def max[A: Ordering](list: List[A]): Option[A] = list match {
  case Nil => None
  case h :: Nil => Some(h)
  case h :: t => if(implicitly[Ordering[A]].gt(h, t.head)) max(h :: t.tail) else max(t)
}

max(List(1,2,8,3,4,6,0)).getOrElse("List is empty") // 8: Any
max(List()).getOrElse("List is empty")              // List is empty: Any

答案 6 :(得分:0)

这是我想出的最简单的方法:

def max(xs: List[Int]): Int = { if (xs.length == 1) xs.head

else if(xs.isEmpty) throw new NoSuchElementException

else if(xs.head > max(xs.tail))  xs.head

else max(xs.tail)}  }

答案 7 :(得分:0)

这有效

def max(xs: List[Int]): Int = xs match{
  case Nil => 0
  case head :: Nil => head
  case head :: tail => max(List(head, max(tail)))
}

答案 8 :(得分:-1)

我的解决方法

  def max(xs: List[Int]): Int = {
    if (xs.isEmpty) 0
    else xs.max
  }
相关问题