Skip to content

Instantly share code, notes, and snippets.

@igorw
Created December 30, 2012 16:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igorw/4413758 to your computer and use it in GitHub Desktop.
Save igorw/4413758 to your computer and use it in GitHub Desktop.
<?php
$factorial = call_user_func(
function ($le) {
return call_user_func(
function ($f) {
return $f($f);
},
function ($f) use ($le) {
return $le(function ($x) use ($f) {
return call_user_func($f($f), $x);
});
}
);
},
function ($factorial) {
return function ($x) use ($factorial) {
if ($x > 0) {
return $x * $factorial($x - 1);
}
return 1;
};
}
);
var_dump($factorial(1));
var_dump($factorial(2));
var_dump($factorial(3));
var_dump($factorial(4));
@MarcelloDuarte
Copy link

I suppose I could use the y combinator, but this is simpler:

<?php

$factorial = function ($x) use (&$factorial) {
    if ($x > 0) {
        return $x * $factorial($x - 1);
    }
    return 1;
};

:)

@MarkBaker
Copy link

Who needs recursion for a factorial though:

function factorial($number)
{
    $factorial = 1;
    while ($number > 1) {
        $factorial *= $number--;
    }
    return $factorial ;
}

@MarcelloDuarte
Copy link

@MarkBaker we can find an iterative solution to almost any problem that we can solve with recursion. The point was to illustrate that it is possible to make a closure recursive in PHP. Which is not a straight forward conclusion, as there is no keyword to refer to the closure itself from within the closure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment