Skip to content

Instantly share code, notes, and snippets.

@mmakowski
Created March 11, 2012 14:02
Show Gist options
  • Save mmakowski/2016537 to your computer and use it in GitHub Desktop.
Save mmakowski/2016537 to your computer and use it in GitHub Desktop.
fp-in-scala: ch05-stream
trait Stream[A] {
def exists(f: A => Boolean): Boolean = foldRight(false)((h, t) => f(h) || t)
def foldRight[B](z: => B)(f: (A, => B) => B): B =
uncons map { case (h ,t) => f(h, t.foldRight(z)(f)) } getOrElse z
def forall(f: A => Boolean): Boolean = foldRight(true)((h, t) => f(h) && t)
def take(n: Int): Stream[A] =
if (n == 0) Stream.empty
else uncons map { case (hd, tl) =>
lazy val rest = tl.take(n - 1)
Stream.cons(hd, rest)
} getOrElse Stream.empty
def takeWhile(f: A => Boolean): Stream[A] = uncons map { case (hd, tl) =>
if (f(hd)) {
lazy val rest = tl.takeWhile(f)
Stream.cons(hd, rest)
} else Stream.empty[A]
} getOrElse Stream.empty
def toList: List[A] = uncons map { case (hd, tl) => hd +: tl.toList} getOrElse (List[A]())
def uncons: Option[(A, Stream[A])]
}
object Stream {
def empty[A]: Stream[A] = new Stream[A] {
def uncons = None
}
def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = new Stream[A] {
lazy val uncons = Some((hd, tl))
}
def apply[A](as: A*): Stream[A] =
if (as isEmpty) empty
else cons(as.head, apply(as.tail: _*))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment