I have the following unit test:
FlattenArray.flatten(
List(0, 2, List(List(2, 3), 8, List(List(100)), null, List(List(null))), -2))
should be(List(0, 2, 2, 3, 8, 100, -2))
With my implementation as follow:
object FlattenArray {
def flatten(list: List[Any]): List[Any] = {
list match {
case Nil => Nil
case (x: List[Any]) :: tail => flatten(x) ::: flatten(tail)
case x :: tail => x :: flatten(tail)
}
}
}
The test if failing because, on case Nil I should add no value to the flatten list: any suggestion on how to do so?
I could filter out from the flatten list null values: is that the correct implementation?
You can add a special case for null :: tail which returns flatten(tail):
def flatten(list: List[Any]): List[Any] = {
list match {
case Nil => Nil
case null :: tail => flatten(tail)
case (x: List[Any]) :: tail => flatten(x) ::: flatten(tail)
case x :: tail => x :: flatten(tail)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With