Skip to content

Instantly share code, notes, and snippets.

@alexmacedo
Created November 27, 2010 14:40
Show Gist options
  • Save alexmacedo/717937 to your computer and use it in GitHub Desktop.
Save alexmacedo/717937 to your computer and use it in GitHub Desktop.
lazy proc implementation in ruby
module Lazy
class LazyProc
alias __class__ class
instance_methods.each { |m| undef_method m unless m =~ /^__/ or m == :object_id }
def initialize(&computation)
@computation = computation
end
def inspect
if @value
@value.inspect
else
"#<#{__class__} computation=#{@computation.inspect}>"
end
end
def respond_to?(method)
method = method.to_sym
method == :inspect or
method == :evaluate or
evaluate.respond_to?(method)
end
def method_missing(method, *args, &block)
evaluate.__send__(method, *args, &block)
end
def evaluate
@value = @computation.call unless @value
@value
end
end
class LispyEnumerable
include Enumerable
def initialize(list)
@list = list
end
def each
while @list
car,cdr = @list
yield car
@list = cdr
end
end
end
end # module
module Kernel
def lazy(&block)
Lazy::LazyProc.new(&block)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment