Skip to content

Instantly share code, notes, and snippets.

@grifx
Last active December 17, 2015 13:00
Show Gist options
  • Save grifx/f7c46f4b3ee7e135b96b to your computer and use it in GitHub Desktop.
Save grifx/f7c46f4b3ee7e135b96b to your computer and use it in GitHub Desktop.
The Little Schemer - Y combinator in PHP
<?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