在這裏你對陣一個元組:
case (x1,x2) => (x2,x2)
如果你要玩與遞歸和模式匹配,你可以做像這樣做:
object HeadTail{
def find(lista: List[Int]) : (Int,Int) = {
@tailrec
def getLast(l: List[Int]): Int = l match {
case h :: Nil => h
case h :: tail => getLast(tail)
}
lista match {
case Nil => throw new IllegalArgumentException("empty list")
case h :: tail => (h, getLast(lista))
}
}
}
這裏它是如何工作:
scala> stackoverflow.q35804673.HeadTail.find(List(1,2,3,4,5))
res0: (Int, Int) = (1,5)
scala> stackoverflow.q35804673.HeadTail.find(List(1,5))
res1: (Int, Int) = (1,5)
scala> stackoverflow.q35804673.HeadTail.find(List(1))
res2: (Int, Int) = (1,1)
scala> stackoverflow.q35804673.HeadTail.find(List.empty)
java.lang.IllegalArgumentException: empty list
什麼是您收到確切的錯誤?它是一個'MatchError'嗎?請相應地更新您的問題。 – Eric
另外,除非這是一個學術練習,爲什麼不嘗試'(lista.head,lista.last)'? – Eric
我知道這是可能的,我只是想不這樣做大聲笑 – miechooy