Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case with no return value

Tags:

match

scala

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?

like image 602
pfari Avatar asked Apr 18 '26 13:04

pfari


1 Answers

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)
  }
}
like image 107
Tzach Zohar Avatar answered Apr 21 '26 06:04

Tzach Zohar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!