Scala flatten List

后端 未结 5 1739
無奈伤痛
無奈伤痛 2020-12-29 11:13

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 :: N         


        
5条回答
  •  盖世英雄少女心
    2020-12-29 11:19

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

提交回复
热议问题