# Why is this code not working?

**URL:** https://discourse.julialang.org/t/why-is-this-code-not-working/37523
**Category:** New to Julia
**Created:** [April 13, 2020, 6:01pm UTC](https://discourse.julialang.org/t/why-is-this-code-not-working/37523 "2020-04-13T18:01:14Z")
**Posts on this page:** 1
**Showing post:** 3

<div class="post-metadata">

### Author: ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)
#### Post date: [April 13, 2020, 6:33pm UTC](https://discourse.julialang.org/t/why-is-this-code-not-working/37523/3 "2020-04-13T18:33:34Z")

</div>

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:

```julia
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:

```julia
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)

```

---

_[View the full topic](https://discourse.julialang.org/t/why-is-this-code-not-working/37523)._
