I wrote the following function to convert List[Int] => List[List[Int]]
.
Its intended purpose is to extract 1
, followed by its non 1
followers, into a group.
input: List(1,2,2,1,3,3)
output: List( List(1,2,2), List(1,3,3) )
Function
def leadingOnesGroup(xs: List[Int]): List[List[Int]] =
xs match {
case Nil => Nil
case _ :: _ =>
val (first, rest) = xs.span(_ == 1)
val (followers, remainder) = rest.span(_ != 1)
(first ++ followers) :: leadingOnesGroup(remainder)
}
Testing
scala> leadingOnesGroup(List(1,2,2))
res19: List[List[Int]] = List(List(1, 2, 2))
scala> leadingOnesGroup(List(1,2,2,1,3,3))
res20: List[List[Int]] = List(List(1, 2, 2), List(1, 3, 3))
scala> leadingOnesGroup(List(1,2,2,1,3,3,1,5,5))
res21: List[List[Int]] = List(List(1, 2, 2), List(1, 3, 3), List(1, 5, 5))