Advertisement
Guest User

Untitled

a guest
Dec 15th, 2014
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.55 KB | None | 0 0
  1. sealed trait Stream[+A]
  2. case object Empty extends Stream[Nothing]
  3. case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]
  4.  
  5. object Stream {
  6.   def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = {
  7.     lazy val head = hd
  8.     lazy val tail = tl
  9.     Cons(() => head, () => tail)
  10.   }
  11.  
  12.   def empty[A]: Stream[A] = Empty
  13.  
  14.   def apply[A](as: A*): Stream[A] =
  15.     if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))
  16.    
  17.   def headOption: Option[A] = this match {
  18.     case Empty => None
  19.     case Cons(h, t) => Some(h())
  20.   }    
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement