Reputation: 954
I unsuccessfully tried to implement the flatten
function in Scala, but did find this implementation here:
def flatten(xs: List[Any]): List[Any] = xs match {
case Nil => Nil
case (head: List[_]) :: tail => flatten(head) ++ flatten(tail)
case head :: tail => head :: flatten(tail)
}
Now, is there any way to write this in terms of if/else
? I'm trying to wrap my head around pattern matching, and it would help to see an if/else implementation of this pattern matching. I understand that (head: List[_]) :: tail
means something like "if xs is a list with a head that's also a list and tail", but can't find a way to rewrite this in terms of if/else. Is pattern matching the same as if/else
, or is it a completely different construct than it? Can all if/else statements be made into pattern matching, and vice versa? Thank you.
Upvotes: 2
Views: 412
Reputation: 12296
Should be something like this:
if (xs.isInstanceOf[List]) {
val lst = xs.asInstanceOf[List]
if (lst == Nil) {
Nil
} else if (lst.head.isInstanceOf[List]) {
flatten(lst.head.asInstanceOf[List]) ++ flatten(lst.tail)
} else {
lst.head :: flatten(lst.tail)
}
}
Upvotes: 1