Simple fibonacci function

julia> function fib(n::Int)
       n<0 && error("n must be non negative")
       n==1 && return 1
       fib(n-1) + fib(n-2)
       end
fib (generic function with 1 method)

julia> fib(2)
ERROR: n must be non negative
Stacktrace:
 [1] error(::String) at .\error.jl:33
 [2] fib(::Int64) at .\REPL[13]:2
 [3] fib(::Int64) at .\REPL[13]:4 (repeats 2 times)
 [4] top-level scope at none:0

I don’t get it !
What am I missing ?

Thanks !

You are missing the basecase for n==0.

n = 2
fib(n-2 =0 )
fib(0-1) 
function fib(n::Int)
              n<0 && error("n must be non negative")
              n==0 && return 0
              n==1 && return 1
              fib(n-1) + fib(n-2)
              end
1 Like

Thanks !
Still, I find it weird the error() message was triggered.
This got me thinking my coding of this line was wrong and that it was acting as < or = :
I had
julia> fib(0)
ERROR: n must be non negative
Stacktrace:
[1] error(::String) at .\error.jl:33
[2] fib(::Int64) at .\REPL[37]:2
[3] fib(::Int64) at .\REPL[37]:4
[4] top-level scope at none:0

julia>

f(0) goes to line three and calls f(-1)

1 Like

Yes, I get that.
I meat to say that what confused me was reading the stack trace :

using the error() made the “n must be non negative” show up in the stack trace
and stop the infinite loop …

With

function fib(n::Int)
      n<0 && println("n must be non negative")
      n==1 && return 1
      fib(n-1) + fib(n-2)
      end

it would have been much clearer as the infinite loop shows up.
I didn’t knew error() would hide this problem.

So should I got back to using println() then and only use when I am sure this kind of issue doesn’t happen ?

I meat to improve my code and it came back at me :sweat_smile:

Note for other newb to prog/Julia: lI got the error() idea form the Julia manual short circuit evaluation part

function fact(n::Int)
           n >= 0 || error("n must be non-negative")
           n == 0 && return 1
           n * fact(n-1)
       end

error throws an ErrorException. If you only wanted to log you can use @error

1 Like