# memoized-recursive-fibonacci using DownValues [closed]

Clear["Global`*"];
fib[n_] :=
If[MemberQ[DownValues[d][[All, 1]] /. {d[x_] :> x, HoldPattern -> Sequence}, n],
Return@d[n],
d[n] = If[n < 3, 1, fib[n - 1] + fib[n - 2]];
Return@d[n]
];

fib[500] == Fibonacci[500] // AbsoluteTiming

Other optional:

DownValues[d][[;; , 1]] /. d | HoldPattern -> Sequence
(DownValues[d][[;; , 1]] /. HoldPattern[d[x_]] :> x)[[;; , 1]]
(DownValues[d] /. HoldPattern[d[x_]] :> x)[[;; , 1, 1]]

My code works, I think the first If statement is not efficiently and refined, How can I improve it?

-
Memoized alternative to using DownValues: mathematica.stackexchange.com/questions/31593/… –  Anon Sep 26 at 14:51
Why do you want to use DownValues btw? It is not required to write a memoized recursive sequence generator for Fibonacci. –  Anon Sep 26 at 14:53
I also don't see why you're using DownValues (the function) directly. It that merely an exercise? By the way, your use of Return is superfluous. –  Mr.Wizard Sep 26 at 16:05
You really -- and I mean really -- need to read this. –  m_goldberg Sep 27 at 2:54
I have closed this until the intent of the question is clarified. If you merely want a memoization-based Fibonacci sequence function it is already shown in Fibonacci Sequence Generator -- if you have other intentions they need to be clarified. –  Mr.Wizard Sep 27 at 8:54