2015-04-05 58 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)),無論你更舒適(他們是同一件事)。

這只是一個起點,隨着您進一步學習,您會發現我的方法不是尾遞歸不太好。您也可以考慮是否可以返回一個選項來解決空列表案例。另外請注意,最大值,最小值,總和,產品......的實現非常相似,並試圖將其分解出來。