我想pattern match
在a的不同部分list
in scala
关于的类型head
and tail
:
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.
}
}
I get:
错误:(18, 17) 类型模式中的非变量类型参数 Int
List[Int] (List[Int] 的基础)未被选中,因为它是
通过擦除消除
case (head: List[Int]) :: (tail: List[Any]) => head.head :: flattenRecur(head.tail :: tail)
^
我缺少什么?我怎么可能在head
and tail
's types名单上的?
我同意 @Andreas 的 HList 解决方案是解决问题的一个很好的例子,但我仍然不明白这有什么问题:
def flatten(ls: List[_]): List[Int] = ls match {
case Nil => Nil
case (a: Int) :: tail => a :: flatten(tail)
case (a: List[_]) :: tail => flatten(a) ::: flatten(tail)
case _ :: tail => flatten(tail)
}
Then:
println(flatten(List(List("one",9,8),3,"str",4,List(true,77,3.2)))) // List(9, 8, 3, 4, 77)
我在您的任务中没有看到类型擦除有任何问题,因为您实际上不需要测试被擦除的类型。我在示例中故意跳过了所有已删除的类型 - 以展示这一点。类型擦除不会清除列表元素的类型信息,它仅清除您拥有的列表泛型的类型信息Any
or _
就我而言 - 所以你根本不需要它。如果我没有遗漏某些内容,那么在您的示例中,类型根本不会被删除,因为无论如何您都有Any
几乎无处不在。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)