Skip to content

Instantly share code, notes, and snippets.

@citizen428
Created June 18, 2009 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save citizen428/131821 to your computer and use it in GitHub Desktop.
Save citizen428/131821 to your computer and use it in GitHub Desktop.
Quick and dirty lazy lists in Ruby, based on Hashes. This is just a quick proof of concept hack, not a real implementation.
class LazyList
def initialize(&block)
@ll = Hash.new &block
end
def take(x)
(1..x).inject([]) { |ret, i| ret << @ll[i] }
end
def take_from(x,y=1)
(0..y-1).inject([]) { |ret, i| ret << @ll[x+i] }
end
def take_while(operand, value)
ret = []
while (i ||= 1)
cur = take_from(i)[0]
break if !cur.send(operand, value)
ret << cur
i += 1
end
ret
end
def [](x)
@ll[x]
end
end
multiples_of_three = LazyList.new { |h, k| h[k] = k*3 }
multiples_of_three.take(3) # => [3, 6, 9]
multiples_of_three[6] # => 18
even_nums = LazyList.new { |h, k| h[k] = k * 2 }
even_nums.take(10) # => [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
even_nums.take_while(:<, 18) # => [2, 4, 6, 8, 10, 12, 14, 16]
squares = LazyList.new { |h,k| h[k] = k*k }
squares.take(5) # => [1, 4, 9, 16, 25]
squares[12] # => 144
squares.take_from(5, 7) # => [25, 36, 49, 64, 81, 100, 121]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment