Created
August 17, 2011 18:39
-
-
Save hexgnu/1152278 to your computer and use it in GitHub Desktop.
Y Combinator in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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