Skip to content

Instantly share code, notes, and snippets.

@schmmd
Created November 20, 2014 16:56
Show Gist options
  • Save schmmd/0c575a56fd80f8b833fd to your computer and use it in GitHub Desktop.
Save schmmd/0c575a56fd80f8b833fd to your computer and use it in GitHub Desktop.
object Unfold extends App {
def read(pos: Int, num: Int): Seq[Int] = {
val data = (0 to 100).toVector
data.drop(pos).take(num)
}
def unfold[A, B](seed: B)(f: B => Option[(B, A)]) = {
def loop(seed: B)(ls: Stream[A]): Stream[A] = f(seed) match {
case Some((b, a)) => loop(b)(a #:: ls)
case None => ls
}
loop(seed)(Stream.empty)
}
def all: Stream[Seq[Int]] = {
val BatchSize = 10
unfold(0) { pos =>
read(pos, BatchSize) match {
case Nil => None
case xs => Some(pos + BatchSize, xs)
}
}.reverse
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment