3

I'm learning Scala and going through 99 Scala problems. For the following exercises:

Flatten a nested list structure. Example:

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

The solution is given as

def flatten(ls: List[Any]): List[Any] = ls flatMap {
  case ms: List[_] => flatten(ms)
  case elements => List(elements)
}

But I was wondering why the following does not work?

def flatten[A](ls: List[List[A]]): List[A] = ls flatMap {
  case ms: List[_] => flatten(ms)
  case elements => List(elements)
}

IntellJ IDEA tells me the issue is with the flatten(ms) part, saying "cannot resolve reference flatten with such a signature" and in the List class documentation for flatten it says "Note: The compiler might not be able to infer the type parameter".

Any ideas why the second code does not work?

I.G. Pascual
  • 5,818
  • 5
  • 42
  • 58
Runner Bean
  • 4,895
  • 12
  • 40
  • 60

2 Answers2

1

Someone else had a different question, but using the same example.

I break down each step and explain it here

Community
  • 1
  • 1
Rhys Bradbury
  • 1,699
  • 13
  • 24
  • 1
    Yes that someone else was me! And I accepted your great detailed informative answer, so thank you. But I feel this is different and was was not explain in that reply (I did not ask it to be explained there). Here I am asking why we cant use the [A] to say this could be of type int or char or whatever. The [A] syntax used in all the other first ten questions on 99 scala problems and when I test myself I'm finding it hard to stop myself using [A] for this example, but I need to as its wrong. But If i knew why it was wrong I may find not trying to use the [A] comes more naturally. – Runner Bean May 26 '16 at 06:14
0

Because last step of unwrapping will fail? You will have List(elements), and second version of flatten requires providing List in List.

michaJlS
  • 2,465
  • 1
  • 16
  • 22