Skip to content

Instantly share code, notes, and snippets.

@mtdowling
Last active March 7, 2018 00:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtdowling/4516558 to your computer and use it in GitHub Desktop.
Save mtdowling/4516558 to your computer and use it in GitHub Desktop.
Fibonacci in PHP using anonymous functions and memoization
<?php
$fibMemo = call_user_func(function () {
$memo = array(0 => 0, 1 => 1);
$fib = function ($n) use (&$memo, &$fib) {
if (!isset($memo[$n])) {
$memo[$n] = $fib($n - 1) + $fib($n - 2);
}
return $memo[$n];
};
return $fib;
});
echo $fibMemo(10);
// >> 55
@rwakos
Copy link

rwakos commented Mar 7, 2018

Awesome!!, it does work, but when does it stop?? Shouldn't be a condition (n<2) return n???, if you put a echo inside the anonymous function you could see that it is doing a doble loop...

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