Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala flatten List

I want to write a function that flats a List.

object Flat {
  def flatten[T](list: List[T]): List[T] = list match {
    case Nil => Nil
    case head :: Nil => List(head)
    case head :: tail => (head match {
      case l: List[T] => flatten(l)
      case i => List(i)
    }) ::: flatten(tail)
  }
}

object Main {
  def main(args: Array[String]) = {
    println(Flat.flatten(List(List(1, 1), 2, List(3, List(5, 8)))))
  }
}

I don't know why it don't work, it returns List(1, 1, 2, List(3, List(5, 8))) but it should be List(1, 1, 2, 3, 5, 8).

Can you give me a hint?

like image 840
Lux Weidling Avatar asked Oct 24 '12 23:10

Lux Weidling


People also ask

What does. flatten do in Scala?

The flatten function is applicable to both Scala's Mutable and Immutable collection data structures. The flatten method will collapse the elements of a collection to create a single collection with elements of the same type.

What is a Flatten list?

Flattening a list of lists is a process of transforming a two-Dimensional list into a One-Dimensional list by un-nesting every list element kept in the list of lists, that is, transforming [[9, 8, 7], [6, 5, 4], [3, 2, 1]] to [9, 8, 7, 6, 5, 4, 3, 2, 1]. ADVERTISEMENT.

What is flatMap in Scala?

In Scala, flatMap() method is identical to the map() method, but the only difference is that in flatMap the inner grouping of an item is removed and a sequence is generated. It can be defined as a blend of map method and flatten method.

What is use of flatten function?

FLATTEN is a table function that takes a VARIANT, OBJECT, or ARRAY column and produces a lateral view (i.e. an inline view that contains correlation referring to other tables that precede it in the FROM clause). FLATTEN can be used to convert semi-structured data to a relational representation.


2 Answers

You don't need to nest your match statements. Instead do the matching in place like so:

  def flatten(xs: List[Any]): List[Any] = xs match {
    case Nil => Nil
    case (head: List[_]) :: tail => flatten(head) ++ flatten(tail)
    case head :: tail => head :: flatten(tail)
  }
like image 109
SDJMcHattie Avatar answered Oct 08 '22 09:10

SDJMcHattie


By delete line 4

case head :: Nil => List(head)

You will get right answer.

Think about the test case

List(List(List(1)))

With line 4 last element in list will not be processed

like image 42
Tim Green Avatar answered Oct 08 '22 08:10

Tim Green