[英]What is the meaning of case in match pattern in scala?
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
}
對於遞歸格式的上述代碼。 誰能解釋為什么我們給出::和case h以及case tail和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)
}
::: List(h)如何工作?
::方法用於構造和解構列表。 a :: b表示列表的開頭是a(單個元素),而結尾是b(列表)。
p :: Nil表示存在某些元素p且尾部為空列表(Nil)的情況。
這種情況基本上是在列表中找到最后一個實際元素。
第二種情況類似:h :: tail表示元素h和列表尾。 因此,我們反轉了尾部,然后將h的列表添加到末尾(l1 ::: l2在列表 l1之前添加了列表 l1)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.