# ajablonski's solution

## to Flatten Array in the Scala Track

Published at Oct 04 2019 · 0 comments
Instructions
Test suite
Solution

Take a nested list and return a single flattened list with all values except nil/null.

The challenge is to write a function that accepts an arbitrarily-deep nested list-like structure and returns a flattened structure without any nil/null values.

For Example

input: [1,[2,3,null,4],[null],5]

output: [1,2,3,4,5]

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command `sbt test` in the exercise directory.

For more detailed info about the Scala track see the help page.

## Source

Interview Question https://reference.wolfram.com/language/ref/Flatten.html

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### FlattenArrayTest.scala

``````import org.scalatest.{Matchers, FunSuite}

/** @version 1.2.0 */
class FlattenArrayTest extends FunSuite with Matchers {

test("no nesting") {
FlattenArray.flatten(List(0, 1, 2)) should be(List(0, 1, 2))
}

test("flattens array with just integers present") {
pending
FlattenArray.flatten(List(1, List(2, 3, 4, 5, 6, 7), 8)) should be(
List(1, 2, 3, 4, 5, 6, 7, 8))
}

test("5 level nesting") {
pending
FlattenArray.flatten(List(0,
2,
List(List(2, 3), 8, 100, 4, List(List(List(50)))),
-2)) should be(
List(0, 2, 2, 3, 8, 100, 4, 50, -2))
}

test("6 level nesting") {
pending
FlattenArray.flatten(List(
1,
List(2, List(List(3)), List(4, List(List(5))), 6, 7),
8)) should be(List(1, 2, 3, 4, 5, 6, 7, 8))
}

test("6 level nest list with null values") {
pending
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))
}

test("all values in nested list are null") {
pending
FlattenArray.flatten(
List(null,
List(List(List(null))),
null,
null,
List(List(null, null), null),
null)) should be(List())
}
}``````
``````import scala.annotation.tailrec

object FlattenArray {
def flatten[T](list: List[Any]): List[T] = tailrecFlatten(list, List.empty[T])

@tailrec
private def tailrecFlatten[T](list: List[Any], result: List[T]): List[T] = list match {
case (h: List[Any]) :: t => tailrecFlatten(h ++ t, result)
case (h: T) :: t => tailrecFlatten[T](t, h :: result)
case null :: t => tailrecFlatten(t, result)
case Nil => result.reverse
}
}``````