在这里你对阵一个元组:
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