Skip to content

Instantly share code, notes, and snippets.

@hexgnu
Created August 17, 2011 18:39
Show Gist options
  • Save hexgnu/1152278 to your computer and use it in GitHub Desktop.
Save hexgnu/1152278 to your computer and use it in GitHub Desktop.
Y Combinator in Ruby
# Define the Y combinator
module Y
extend self
def combinator(&generator)
lambda do |x|
lambda do |*args|
generator.call(x.call(x)).call(*args)
end
end.call(lambda do |x|
lambda do |*args|
generator.call(x.call(x)).call(*args)
end
end)
end
end
# Call the Y combinator, providing it with a procedure that
# accepts a recursive callback function and returns a procedure.
# The Y combinator returns the recursive function. Then call that
# function to produce a Hash object.
hash = Y.combinator do |callback|
lambda do
Hash.new { |h, k| h[k] = callback.call }
end
end.call
# Now this will work:
hash['a']['b']['c']['d']['e']['f']['g'] = 1
# => {"a"=>{"b"=>{"c"=>{"d"=>{"e"=>{"f"=>{"g"=>1}}}}}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment