I would like to pattern match
on different segments of a list
in scala
on the types of the 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:
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) ^
What am I missing? how is it possible for me to pattern match on the head
and tail
's types of the list?
case (head: List[Int]) :: (tail: List[Any]) =>
withcase ( (headhead : Int) :: (headtail : List[Any]) ) :: (tail : List[Any]) =>
That would allow you to fight type erasure – ayvangocase (head: List[Any]) :: (tail: List[Any])
you have mentioned a different line, is that supposed to help that line as well??? – Jascase (head: List[Any]) :: (tail: List[Any])
because its conflicting? – Jashead
is of type List[Int] that lacks description. So you should expandhead
further toheadhead :: headtail
. Now scala would catch types – ayvango