Skip to content

Instantly share code, notes, and snippets.

@alandipert
Created May 7, 2011 20:42
Show Gist options
  • Save alandipert/960822 to your computer and use it in GitHub Desktop.
Save alandipert/960822 to your computer and use it in GitHub Desktop.
Clojure-inspired fibonacci streams with Fibers
require 'fiber'
class Fiber
def map &block
Fiber.new { loop { Fiber.yield block.call(resume) } }
end
def to_a
[].tap{|xs| xs << resume while alive?}
end
def take n
Fiber.new do
(n-1).times { Fiber.yield resume }
resume
end
end
def self.iterate x,&block
Fiber.new do
loop do
Fiber.yield x
x = block.call(x)
end
end
end
end
fibs = Fiber.iterate([1,0]){|(a,b)|[b,a+b]}.map(&:last)
p fibs.take(10).to_a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment