1

I want to create a flatten function, which will take List of various depth and transform it to a flat list.

For example, for integers it can take List(1, List(2, 3)) and return List(1, 2, 3).

How to declare this function correctly?

def flatten(list: List[???]): List[T]

3
  • So you want every element of your recursive list to be either type A (Int, in this case) or RecursiveList[A]? Commented Aug 19, 2015 at 17:39
  • OK. Now, since the title of your question is "How to define a recursive list type?", I guess you understand that that type has to be created before you can create a flatten function. It's just that the actual text of your question makes no mention of that and only talks about the function. Would an answer which shows how to create RecursiveList[A] and then the function def flatten[A](xs: RecursiveList[A]): List[A] be what you want? Commented Aug 20, 2015 at 14:01
  • Because you can't arbitrarily create lists that may contain either elements or also lists of elements in Scala (unless you choose Aleksey's solution of List[Any). Scala lists are homogenous. Commented Aug 20, 2015 at 14:08

1 Answer 1

2

Looks like you have to use Any because the depth of the list is unknown.

def flatten(input: List[Any]): List[Any] =
    input match {
      case Nil => Nil
      case head :: tail =>
        head match {
          case list: List[_] => flatten(list) ::: flatten(tail)
          case elem => elem :: flatten(tail)
        }
    }

scala> flatten(List(1, List(2, 3)))
res0: List[Any] = List(1, 2, 3)

If you want to see couple implementation options check here, and tests are here.

Sign up to request clarification or add additional context in comments.

1 Comment

The problem with this is that it allows input of type List(1, "foo", false) and I'm pretty sure the OP wants all the non-list elements to be the same type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.