Skip to content

Instantly share code, notes, and snippets.

@DeepSky8
Last active August 29, 2015 14:02
Show Gist options
  • Save DeepSky8/8bc992d045a3ba6f5fca to your computer and use it in GitHub Desktop.
Save DeepSky8/8bc992d045a3ba6f5fca to your computer and use it in GitHub Desktop.
P09 (**) Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists. Example: scala> pack(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)) res0: List[List[Symbol]] = List(List('a, 'a, 'a, 'a), List('b), List('c, 'c), List('a, 'a), List('d), List('e, 'e,…
def pack[A](input: List[A]): List[List[A]] = input match {
case Nil => Nil
case h :: t => input.filter(_ == input.head) :: pack(packHelper(input.tail))
}
def packHelper[A](input: List[A]): List[A] = input match {
case Nil => Nil
case h :: t => input.filterNot(_ == input.head)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment