Skip to content

Instantly share code, notes, and snippets.

@dvapelnik
Created February 6, 2016 22:54
Show Gist options
  • Save dvapelnik/540ac98462a821800837 to your computer and use it in GitHub Desktop.
Save dvapelnik/540ac98462a821800837 to your computer and use it in GitHub Desktop.
Y-Combinator in PHP
<?php
// Source: https://php100.wordpress.com/2009/04/13/php-y-combinator/
function Y($F)
{
$func = function ($f) {
return $f($f);
};
return $func(
function ($f) use ($F) {
return $F(
function ($x) use ($f) {
$ff = $f($f);
return $ff($x);
}
);
}
);
}
$factorial = Y(
function ($fact) {
return function ($n) use ($fact) {
return ($n <= 1)
? 1
: $n * $fact($n - 1);
};
}
);
var_dump($factorial(6));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment