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))
}
}
}
}
您的第二種情況應該是'case Cons(x,xs)=> maximum(xs)' – Lee 2015-04-05 15:55:47
因爲沒有爲IntList定義max函數,所以先定義它。 – curious 2015-04-05 15:58:39
@Lee這是不正確的,因爲如果我試圖得到一個列表的最大值,它將返回0由於情況1和情況2不做任何speciefiec。它只需要尾巴等。 – Alex 2015-04-05 15:59:33