Last active
December 17, 2015 13:00
-
-
Save grifx/f7c46f4b3ee7e135b96b to your computer and use it in GitHub Desktop.
The Little Schemer - Y combinator in PHP
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
<?php | |
/** | |
* “The Little Schemer” - Y combinator in PHP | |
* @author: Joris Garonian | |
*/ | |
function Y($g) { | |
return call_user_func(function ($f) { | |
return $f($f); | |
}, function ($f) use ($g) { | |
return $g(function ($x) use ($f) { | |
return call_user_func($f($f), $x); | |
}); | |
}); | |
} | |
$factorial = Y(function ($x) { | |
return function ($n) use ($x) { | |
return $n <= 2 ? $n : $n * $x($n - 1); | |
}; | |
}); | |
echo $factorial(3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment