Skip to content

Instantly share code, notes, and snippets.

@alinpopa
Created January 20, 2010 20:13
Show Gist options
  • Save alinpopa/282199 to your computer and use it in GitHub Desktop.
Save alinpopa/282199 to your computer and use it in GitHub Desktop.
object LazyFib {
implicit def wrapStreamInt(s:Stream[Int]) = new StreamWrapper[Int](s)
def apply(n:Int):List[Int] = fibs().takeN(n)
def zipWith(f:(Int,Int) => Int, l1:Stream[Int], l2:Stream[Int]):Stream[Int] = {
l1.zip(l2).map{x:(Int,Int) => f(x._1, x._2)}
}
def fibs():Stream[Int] = Stream.cons(0, Stream.cons(1, zipWith((x:Int,y:Int) => x+y, fibs, fibs.tail)))
}
class StreamWrapper[A](val value:Stream[A]) {
def takeN(i:Int):List[A] = {
var list:List[A] = Nil
for(x <- 0 to i) list = list ::: List(value(x))
list
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment