Last active
August 29, 2015 14:13
-
-
Save bdkosher/5399732f4288f9e90000 to your computer and use it in GitHub Desktop.
Trying to understand Y Combinators using Groovy syntax.
This file contains 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
/* | |
* Follows http://www.righto.com/2009/03/y-combinator-in-arc-and-java.html blog | |
*/ | |
// standard factorial closure | |
def fact = { n -> n == 0 ? 1 : n * call(n - 1) } | |
// factorial closure generator, which requires the factorial closure as an arg (mind blown already) | |
def factGen = { factFn -> | |
{ n -> n == 0 ? 1 : n * factFn(n - 1) } | |
} | |
assert factGen(null)(0) == 1 | |
try { | |
factGen(null)(1) // should fail | |
assert false | |
} catch (fail) { | |
assert fail in NullPointerException | |
} | |
assert factGen(factGen(null))(1) == 1 | |
assert factGen(factGen(factGen(factGen(factGen(null)))))(4) == 24 | |
// The Y combinator in Groovy | |
def Y = { r -> | |
({ f -> f(f) })({ f -> | |
r({ x -> (f(f))(x) }) | |
}) | |
} | |
assert (Y(factGen))(10) == 3628800 | |
// doing it using anonymous closures | |
assert (({ r -> | |
({ f -> f(f) })({ f -> | |
r({ x -> (f(f))(x) }) | |
}) | |
})({ factFn -> | |
{ n -> n == 0 ? 1 : n * factFn(n - 1) } | |
}))(10) == 3628800 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment