Why is this code not working?

First, when you post something like that, it is good to use
```julia
code here
```
to make the code more readable. It becomes this way:

global fib_cache = Dict{BigInt, BigInt}(0 => 0, 1 => 1)
function fib(n::Integer)
    global fib_cache
    get!(fib_cache, BigInt(n), fib(n‑1) + fib(n‑2))
end

It is also good to say how the code is not working, with which values did you test? The code finishes in error, with an wrong answer, or does it just never returns?

Second, your problem is that fib(n‑1) + fib(n‑2) is not lazy, so it will be computed anyway, even if there is a value in the cache. And as you do not consider negative values, it ends in a “infinite” recursive call with negative values as parameters.

The code below solves this problems:

fib_cache = Dict{BigInt, BigInt}(0 => 0, 1 => 1)
function fib(n::Integer)
  n < zero(n) && @error "negative parameter n ($n) for fib"
  global fib_cache
  get!(fib_cache, BigInt(n)) do
    fib(n - 1) + fib(n - 2)
  end 
end

@show fib(0)
@show fib(1)
@show fib(2)
@show fib(3)
@show fib(4)
#@show fib(-1)
4 Likes