Created
February 2, 2012 01:05
-
-
Save dholbrook/1720567 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package scalaninetynine | |
/* | |
* S99 P09 http://aperiodic.net/phil/scala/s-99/ | |
* 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, 'e, 'e)) | |
* | |
* D. Holbrook 2012-01-31 | |
*/ | |
object S9909 extends App { | |
def pack[A](l: List[A]): List[List[A]] = { | |
l.foldLeft(List(List[A]())) { | |
case (acc, i) if acc.head == Nil || acc.head.head == i => (i :: acc.head) :: acc.tail | |
case (acc, i) => List(i) :: acc | |
}.reverse | |
} | |
val r = pack(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)) | |
assert(r == List(List('a, 'a, 'a, 'a), List('b), List('c, 'c), List('a, 'a), List('d), List('e, 'e, 'e, 'e))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment