2015-04-05 60 views
1

我正在写一个函数,它会在IntList中找到最大的元素。我知道如何在Java中做到这一点,但无法理解如何在Scala上做到这一点。如何在IntList中查找最大值?

我做到了,这是我到目前为止,我认为这应该是它。

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)) 
      } 
     } 
     } 
} 
+0

您的第二种情况应该是'case Cons(x,xs)=> maximum(xs)' – Lee 2015-04-05 15:55:47

+0

因为没有为IntList定义max函数,所以先定义它。 – curious 2015-04-05 15:58:39

+0

@Lee这是不正确的,因为如果我试图得到一个列表的最大值,它将返回0由于情况1和情况2不做任何speciefiec。它只需要尾巴等。 – Alex 2015-04-05 15:59:33

回答

0

模式匹配将使它更短:

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 
} 

次要笔记:

  • 你可以改变的情况下类无()来区分对象无
  • 最后两行应该只是head max maximum(tail)head.max(maximum(tail)),无论你更舒适(他们是同一件事)。

这只是一个起点,随着您进一步学习,您会发现我的方法不是尾递归不太好。您也可以考虑是否可以返回一个选项来解决空列表案例。另外请注意,最大值,最小值,总和,产品......的实现非常相似,并试图将其分解出来。