Guest User

Untitled

a guest
Jul 21st, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. <?php
  2.  
  3. class DynamicClosure {
  4. public static function execute(Closure $closure) {
  5. return call_user_func($closure);
  6. }
  7. }
  8.  
  9.  
  10. echo '<br/>Standard factorial<br/>';
  11.  
  12. function factorial($n) {
  13. echo 'call <br/>';
  14. if ($n == 0) {
  15. return 1;
  16. } else {
  17. return $n * factorial($n - 1);
  18. }
  19. }
  20.  
  21. echo factorial(10) . '<br/>'; // called 11 times
  22. echo factorial(11) . '<br/>'; // called 12 times
  23. echo factorial(8) . '<br/>'; // called 8 times
  24.  
  25. echo '<br/>Memoized factorial<br/>';
  26.  
  27. $memoizedFactorial = DynamicClosure::execute(function(){
  28.  
  29. // results are cached in an array
  30. $results = array();
  31.  
  32. // the function is passing itself as a bound variable
  33. return $factorial = function($n) use(&$results, &$factorial) {
  34. echo 'call <br/>';
  35. if (!isset($results[$n])) {
  36. if ($n == 0) {
  37. $results[$n] = 1;
  38. } else {
  39. $results[$n] = $n * $factorial($n - 1);
  40. }
  41. }
  42. return $results[$n];
  43. };
  44. });
  45.  
  46. echo $memoizedFactorial(10) . '<br/>'; // called 11 times
  47. echo $memoizedFactorial(11) . '<br/>'; // called only 2 times!
  48. echo $memoizedFactorial(8) . '<br/>'; // called only 1 times!
Add Comment
Please, Sign In to add comment