Skip to content

Instantly share code, notes, and snippets.

@plexus
Created October 7, 2013 10:43
Show Gist options
  • Save plexus/6865894 to your computer and use it in GitHub Desktop.
Save plexus/6865894 to your computer and use it in GitHub Desktop.
class Lazy < BasicObject
def initialize(&blk)
@blk = blk
end
def method_missing(name, *args, &blk)
_resolve.send(name, *args, &blk)
end
def respond_to?(name)
_resolve.respond_to?(name)
end
def _resolve
@resolved ||= @blk.()
end
end
def lazy(&blk)
Lazy.new(&blk)
end
Cons = Struct.new(:car, :cdr) do
include Enumerable
def each(&blk)
return to_enum unless blk
blk.(car)
cdr.each(&blk)
end
end
# Infinite list of factorials
def fact_list(start = 1, acc = 1)
Cons[start * acc, lazy { fact_list(start + 1, start * acc) }]
end
fact_list.take(5) # => [1, 2, 6, 24, 120]
# Circular lists
fizz = Cons['', Cons['', Cons['Fizz', ]]]
fizz.cdr.cdr.cdr = fizz
buzz = Cons['', Cons['', Cons['', Cons['', Cons['Buzz', ]]]]]
buzz.cdr.cdr.cdr.cdr.cdr = buzz
fizz_enum, buzz_enum = [fizz,buzz].map(&:each)
15.times do |i|
fizzbuzz = [fizz_enum, buzz_enum].map(&:next).join
puts fizzbuzz.empty? ? i+1 : fizzbuzz
end
# >> 1
# >> 2
# >> Fizz
# >> 4
# >> Buzz
# >> Fizz
# >> 7
# >> 8
# >> Fizz
# >> Buzz
# >> 11
# >> Fizz
# >> 13
# >> 14
# >> FizzBuzz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment