List 如何在整数列表中找到最大值?

List 如何在整数列表中找到最大值?,list,scala,max,List,Scala,Max,我正在编写一个函数,它将查找IntList中最大的元素。我知道如何在Java中做到这一点,但不知道如何在Scala中做到这一点 我做到了,这是我到目前为止所拥有的,我想这应该就是了 abstract class IntList case class Nil() extends IntList case class Cons(h: Int, t: IntList) extends IntList object ListFuns { // return the maximum number

我正在编写一个函数,它将查找IntList中最大的元素。我知道如何在Java中做到这一点,但不知道如何在Scala中做到这一点

我做到了,这是我到目前为止所拥有的,我想这应该就是了

abstract class IntList
case class Nil() extends IntList
case class Cons(h: Int, t: IntList) extends IntList

object ListFuns {
   // return the maximum number in is
   // return the maximum number in is
   def maximum(is: IntList): Int = is match {
      case Nil() => 0
      case list => max(head(is), tail(is))
   }

   def head(l : IntList) : Int = l match {
      case Nil() => 0
      case Cons(e,tail) => e
   }

   def tail(l : IntList) : IntList = l match {
      case Nil() => Nil()
      case Cons(e,tail) => tail
   }

   def max(n : Int, l : IntList) : Int = l match {
      case Nil() => n
      case l => {
          val h = head(l)
          var champ = 0
          if(n > h) {
            champ = n 
            n
          }
          else{
            champ = h
            h
          } 
          if(tail(l) == Nil()){
            champ
          }
          else{
            max(champ, tail(l))
          }
        }
      }
}

模式匹配将使其更短:

def maximum(l: IntList) : Int = l match {
   case Cons(singleValue, Nil) => singleValue
   case Nil() => // you decide, 0, the min value of ints, throw....
   case Cons(head, tail) => 
      val maxOfTail = maximum(tail)
      if(maxOfTail > head) maxOfTail else head
}
小调:

您可以将case类Nil更改为case对象Nil 最后两行应该是head-max-maximumtail或head.maximumtail,无论哪一行您更熟悉,它们都是相同的。
这只是一个起点,当您进一步学习时,您会发现我的方法不是尾部递归的,这并不太好。您还可以考虑是否可以返回一个选项来解释空列表的情况。另外,请注意最大值、最小值、总和、乘积的实现。。。都很相似,试着把它考虑进去

第二种情况应该是case Consx,xs=>maximumxs,因为没有为IntList定义max函数,所以请先定义它。@Lee这并不正确,因为如果我尝试获取列表的max,它将返回0,因为情况1,情况2也没有做任何特殊的事情。它只需要尾部等等。是的,您需要通过递归调用遍历当前最大值,并在达到Nil时返回它。在Cons情况下,您不能合理地忽略x。这很可能是最大值。另外,请注意,仅包含负数的列表不会因为为零而提升为0 mas。