Skip to content

Instantly share code, notes, and snippets.

@gnab
Created March 9, 2010 18:40
Show Gist options
  • Save gnab/326925 to your computer and use it in GitHub Desktop.
Save gnab/326925 to your computer and use it in GitHub Desktop.
class Seq
def self.unfold(*initial_state, &producer)
self.new(*initial_state, &producer)
end
def take_while(&condition)
current, state = @producer.call(@initial_state)
seq = [current]
while condition.call(current) do
current, state = @producer.call(state)
seq << current
end
seq
end
private
def initialize(*initial_state, &producer)
@initial_state = initial_state
@producer = producer
end
end
limit = 10**999
fibonacci = Seq.unfold(0, 1) { |current, upcoming| [current, [upcoming, current + upcoming]] }
term = fibonacci.take_while{ |n| n < limit }.size
puts term
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment