Lazy Fibonacci numbers

A function which lazily produce fibonacci numbers implemented in some popular languages.

Haskell

let fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
take 10 fibs
> [0,1,1,2,3,5,8,13,21,34]

Clojure

(def fibs (lazy-cat [0 1] (map + fibs (rest fib))))
(take 10 fibs)
> (0 1 1 2 3 5 8 13 21 34)

Scala

val fibs: Stream[Int] = 0 #:: 1 #:: fibs.zip(fibs.tail).map { n => n._1 + n._2 }
fibs take 10 toList
> List(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)

Ruby

Using Enumerator::Lazy

def fibs
Enumerator.new do |yielder|
yielder << 0 << 1
fibs.lazy.zip(fibs.lazy.drop(1)).each do |a,b|
yielder << a + b
end
end
end
fibs.take(10)
> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Python3

from itertools import islice, tee
from operator import add
def fibs():
yield 0; yield 1
fibs1, fibs2 = tee(fibs())
yield from map(add, fibs1, islice(fibs2, 1, None))
list(islice(fibs(), 0, 10))
> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Java

IntStream fibs = Stream.iterate(
new int[] {0, 1},
p -> new int[] {p[1], p[0] + p [1]}
).mapToInt(p -> p[0]);
fibs.limit(10).boxed().collect(toList());
> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

JavaScript

Using lazy.js

var fibs = Lazy.generate(function() {
var x = 0, y = 1;
return function() {
var prev = x;
x = y;
y += prev;
return prev;
};
}());
fibs.take(10).toArray();
> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

comments powered by Disqus