Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package org.examples
object StreamExamples {
// group List(1,1,2,2,2,3,4,4) =>
// List(List(1,1), List(2,2,2), List(3), List(4,4))
def group[A](s: Stream[A]): Stream[List[A]] =
s match {
case Stream() => Stream.empty
case hd #:: tl =>
val (dups, tail) = tl partition (_ == hd)
(hd :: dups.toList) #:: group(tail)
}
// group Stream(1,1,2,2,2,3,4,4) =>
// Stream(List(1,1), ?)
// Stream(List(1,1), List(2,2,2), ?)
// Stream(List(1,1), List(2,2,2), List(3), ?)
// Stream(List(1,1), List(2,2,2), List(3), List(4))
def testStreamExamples() = {
val s = group(Stream(1,1,2,2,2,3,4,4))
(s take 1) foreach println
println(s) // Stream(List(1, 1), ?) (1)
(s take 2) foreach println
println(s) // Stream(List(1, 1), List(1, 1), ?) (2)
(s take 3) foreach println
println(s) // Stream(List(1, 1), List(2, 2, 2), ?) (3)
(s take 4) foreach println
println(s) // Stream(List(1, 1), List(2, 2, 2), List(3), ?) (4)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment