Skip to content

Instantly share code, notes, and snippets.

@betawaffle
Created March 25, 2012 21:00
Show Gist options
  • Save betawaffle/2199724 to your computer and use it in GitHub Desktop.
Save betawaffle/2199724 to your computer and use it in GitHub Desktop.
Ruby Y Combinator
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
@betawaffle
Copy link
Author

And for hash autovivification:

-> { Hash.new do |h, k| h[k] = self[] end }.y[]

@betawaffle
Copy link
Author

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