Skip to content

Instantly share code, notes, and snippets.

@drupol
Last active November 10, 2020 14:46
Show Gist options
  • Select an option

  • Save drupol/b9eb66e1a7899dff22de38f5b780f9be to your computer and use it in GitHub Desktop.

Select an option

Save drupol/b9eb66e1a7899dff22de38f5b780f9be to your computer and use it in GitHub Desktop.
factorial.php
<?php
// Programmation imperative
$factorial = static function(int $x): int {
$factorial = 1;
for ($i = 2; $i <= $x; $i++) {
$factorial *= $i;
}
return $factorial;
};
// Programmation déclarative
$factorial = static function (int $x) use (&$factorial): int
{
return $x === 2 ? $x : $x * $factorial($x - 1);
};
/*
1: 5 * $factorial(4)
2: 5 * 4 * $factorial(3)
3: 5 * 4 * 3 * $factorial(2)
4: 5 * 4 * 3 * 2 * $factorial(1)
5: 5 * 4 * 3 * 2 * 1
6: 5 * 4 * 3 * 2
7: 5 * 4 * 6
8: 5 * 24
9: 120
*/
// Tail call optimization (https://en.wikipedia.org/wiki/Tail_call)
$factorial = static function(int $x, int $carry = 1) use (&$factorial): int
{
return $x === 1 ? $carry : $factorial($x - 1, $carry * $x);
};
/*
1: $factorial(5, 1);
2: $factorial(4, 5);
3: $factorial(3, 20);
4: $factorial(2, 60);
5: $factorial(1, 120);
6: 120
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment