我想在scala
上list
的不同環節pattern match
的類型而head
和tail
的:如何模式匹配scala列表的頭部和尾部類型?
class Solution07 extends FlatSpec with ShouldMatchers {
"plain recursive flatten" should "flatten a list" in {
val list1 = List(List(1, 1), 2, List(3, List(5, 8)))
val list1Flattened = List(1, 1, 2, 3, 5, 8)
flattenRecur(list1) should be (list1Flattened)
}
def flattenRecur(ls: List[Any]): List[Int] = ls match {
case (head: Int) :: (tail: List[Any]) => head :: flattenRecur(tail)
case (head: List[Int]) :: (tail: List[Any]) => head.head :: flattenRecur(head.tail :: tail)
case (head: List[Any]) :: (tail: List[Any]) => flattenRecur(head) :: flattenRecur(tail) // non-variable type... on this line.
}
}
我得到:
Error:(18, 17) non-variable type argument Int in type pattern List[Int] (the underlying of List[Int]) is unchecked since it is eliminated by erasure case (head: List[Int]) :: (tail: List[Any]) => head.head :: flattenRecur(head.tail :: tail) ^
我缺少什麼?怎麼可能對我來說,模式匹配的head
和tail
的類型名單?
嘗試用case((headhead:Int)::(headtail:List [Any]))替換case(head:List [Int])::(tail:List [Any])=>' (尾:列表[任何])=>'這將允許你與類型擦除 – ayvango
問題是行'case(head:List [Any])::(tail:List [Any])''你提到了一個不同的線路,是否應該幫助該線路? – Jas
第三選擇與第二選擇衝突。所以你可以調整第二選擇或第三選擇。由於第三種選擇更通用,因此更容易製作第二種更具體的 – ayvango