-1

I have jumped into Scala and started doing scala99, but I am stuck at P07 (flattening of list) following is my code and error message from the repl

scala> def flatten[A](x: List[A]): List[A] =
 | for(i <- x) yield i match {
 | case lst: List[Any] => flatten(lst)
 | case e => List(e)
 | }
<console>:12: error: type mismatch;
found   : List[List[Any]]
required: List[A]
   for(i <- x) yield i match {
         ^

Where am I wrong and what is the correct way? Thanks.

Anmol Gautam
  • 949
  • 1
  • 12
  • 27
  • 2
    The first thing that I can see is that your argument type is a `List[A]` instead of a `List[List[A]]`, as for the former there is nothing to "flatten". Also, why match on `List[Any]`? – Yuval Itzchakov Nov 02 '17 at 19:53
  • 1
    @YuvalItzchakov I don't get it: why is it _expecting_ `List[Any]` at that place? `for(i <- x)` is perfectly valid when `x` is `List[A]` ... – Dima Nov 02 '17 at 20:01

2 Answers2

1

Like I said in my comment to your question, I don't know why the compiler complains the way it does, but the root of the problem is that you are returning the same type as the input: if you flatten List[List[Int]] the output will be List[Int], so what would the A be in your code???

I don't think type parameter really serves any purpose in this case, you are better off going with just List[Any]:

  def flatten(in: List[Any], out: List[Any] = Nil): List[Any] = in match { 
    case Nil => out.reverse
    case Nil :: t => flatten(t, out)
    case (h :: t) :: tail => flatten(h :: t ::: tail, out)
    case h :: t => flatten(t, h :: out)
  }
Dima
  • 39,570
  • 6
  • 44
  • 70
-1

I'd use something like this

def flatten(t: List[Any]): List[Any]
  = t.flatMap {
        case s: List[_] => flatten(s)
        case x => List(x)
      }

In your case, the compiler complains because the function body clearly returns value of type List[List[_]] and there's nothing that makes A derivable from that type. At the same time, you cannot make A derivable from List since the top level list may contain scalar values. Finally, your code does not actually flatten the input, it just wraps every scalar value in a single element list.

Alex K
  • 34
  • 4