Created
January 14, 2013 21:45
-
-
Save graue/4533823 to your computer and use it in GitHub Desktop.
X combinator (like the Y combinator) in Lua
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
-- traditional fixed-point operator from functional programming | |
Y = function (f) | |
return (function (x) | |
return x(x) | |
end)(function (x) | |
return f(function (v) | |
return (x(x))(v) | |
end) | |
end) | |
end | |
-- The above is actually the X combinator, according to Wikipedia: | |
-- X = λf.(λx.x x) (λx.f (x x)) | |
-- except that | |
-- (x x) | |
-- has been beta-expanded, yielding | |
-- (λv.((x x) v)) | |
-- which is a necessary change because Lua is call-by-value and strict. | |
-- Without this beta-expansion, the combinator would cause a stack overflow. | |
-- | |
-- Based on code from https://github.com/mherkender/lua.js/blob/master/tests/factorial.lua |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment