Skip to content

Instantly share code, notes, and snippets.

@dseeni
Forked from graue/x_combinator.lua
Created September 11, 2023 11:42
Show Gist options
  • Select an option

  • Save dseeni/2091cd570c135a08ae35874466b66495 to your computer and use it in GitHub Desktop.

Select an option

Save dseeni/2091cd570c135a08ae35874466b66495 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