0
val list1 = List(1, 1, 2, 3, 5,7,8,4)
def lastrecursive[A](ls :List[A]):A = ls match{
case p :: Nil => p // what is the meaning of Nil
case _ :: tail => lastrecursive(tail)
case _ => throw new NoSuchElementException
}
对于ABOVE递归格式的代码。任何人都可以解释我们为什么给 ::和案件h和案件尾部和案件_。同时处理列表匹配模式。scala中匹配模式中case的含义是什么?
and for reversing a list
def reverseRecursive[A](ls: List[A]): List[A] = ls match {
case Nil => Nil
case h :: tail => reverseRecursive(tail) ::: List(h)
}
how this ::: List(h)works?
那么......我相信在这种情况下,使用单词'method'而不是'operator'是一个更好的选择。 '::'不用于构造或解构列表。它实际上是一个'将'元素预加载到'列表'的正确联想方法。当你看到'p :: Nil'时,那么'Nil'是'p'前置的空列表。 –
@SarveshKumarSingh。你是对的 - 更新。 –
“操作符”是一个非常标准的词,具有非常标准的含义。它不是“非字母数字名称的方法名称”。我会建议你在谈论Scala时避免使用“operator”这个词。 –