Skip to content

Instantly share code, notes, and snippets.

@graue
Created January 14, 2013 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save graue/4533823 to your computer and use it in GitHub Desktop.
Save graue/4533823 to your computer and use it in GitHub Desktop.
X combinator (like the Y combinator) in Lua
-- 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