Scala List function for grouping consecutive identical elements

后端 未结 8 2270
悲&欢浪女
悲&欢浪女 2020-12-05 08:00

Given e.g.:

List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)

I\'d like to get to:

List(List(5), List(2), List(3, 3, 3), List(5, 5),         


        
8条回答
  •  情话喂你
    2020-12-05 08:31

    Here's a slightly cleaner one:

    def groupConsequtive[A](list: List[A]): List[List[A]] = list match {
      case head :: tail =>
        val (t1, t2) = tail.span(_ == head)
        (head :: t1) :: groupConsequtive(t2)
      case _ => Nil  
    }
    

    tail-recursive version

    @tailrec
    def groupConsequtive[A](list: List[A], acc: List[List[A]] = Nil): List[List[A]] = list match {
      case head :: tail =>
        val (t1, t2) = tail.span(_ == head)
        groupConsequtive(t2, acc :+ (head :: t1))
      case _ => acc
    }
    

提交回复
热议问题