Подтвердить что ты не робот

Scala flatten 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)))))
  }
}

Я не знаю, почему он не работает, он возвращает List(1, 1, 2, List(3, List(5, 8))), но он должен быть List(1, 1, 2, 3, 5, 8).

Можете ли вы дать мне подсказку?

4b9b3361

Ответ 1

Строкой delete 4

case head :: Nil => List(head)

Вы получите правильный ответ.

Подумайте о тестовом случае

List(List(List(1)))

В строке 4 последний элемент в списке не будет обрабатываться

Ответ 2

Вам не нужно вставлять ваши утверждения соответствия. Вместо этого выполните сопоставление так:

  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)
  }

Ответ 3

My, что эквивалентно решению SDJMcHattie.

  def flatten(xs: List[Any]): List[Any] = xs match {
    case List() => List()
    case (y :: ys) :: yss => flatten(y :: ys) ::: flatten(yss)
    case y :: ys => y :: flatten(ys)
  } 

Ответ 4

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