-
-
Save betawaffle/2199724 to your computer and use it in GitHub Desktop.
Ruby Y Combinator
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
def Y f = nil, &b | |
f ||= b; -> g { g[g] }.call -> g { f[-> *a { g[g][*a] }] } | |
end | |
# Hash Autovivification | |
Y { |d| -> { Hash.new do |h, k| h[k] = d[] end }[] | |
# Factorial | |
Y -> fac { -> n { n <= 2 ? n : n * fac[n - 1] } } | |
# Alternate Using Monkey-Patched Proc | |
Proc.class_eval do | |
def y | |
this = self | |
-> g { g[g] }[-> g { -> *a { g[g].instance_exec *a, &this } }] | |
end | |
end | |
# Factorial | |
-> n { n <= 2 ? n : n * self[n - 1] }.y[5] | |
# => 120 |
fix1 = ->f{->g{g[g]}[->g{f[->*a{g[g][*a]}]}]}
fix2 = ->f{->g{g[g]}[->g{->*a{g[g].instance_exec(*a,&f)}}]}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And for hash autovivification: