Two equivalent codes but one returning error

I was wondering if the two codes are different, because the second one returns an error message of “invalid index : nothing of type Nothing”

ind_one_y = findfirst(surplus[q,:,x,2,mq] .> 0.0) 

Code 1 :     
if isnothing(ind_one_y) == true 
   thr_one_y = 1e+8
else thr_one_y = grids.y[ind_one_y] - grids.mq[mq]
end 

Code 2 :
thr_one_y = ifelse(isnothing(ind_one_y) == true, 1e+8, grids.y[ind_one_y] - grids.mq[mq])

I’m just completely lost.

ifelse behaves like functions do, all its arguments are evaluated. This includes grids.y[ind_one_y], which then errors.

3 Likes

Thank you very much. I didn’t realize there is such subtle difference.

BTW the == true in boolean == true is redundant.

2 Likes

Thank you for pointing that out. A silly mistake :slight_smile:

Note that Julia has a ?: ternary operator like C/C++/Java and many other languages, so you can do:

thr_one_y = isnothing(ind_one_y) ? 1e+8 : grids.y[ind_one_y] - grids.mq[mq]

If you want to do it in a single-line.

2 Likes

Like the ternary ?: operator, the if-else form can also be done in one line if each branch is 1 full line:

# OP's code
if isnothing(ind_one_y) == true   thr_one_y = 1e+8  else  thr_one_y = grids.y[ind_one_y] - grids.mq[mq]  end 

# equivalent to Henrique's edit
thr_one_y = if isnothing(ind_one_y) 1e+8 else grids.y[ind_one_y] - grids.mq[mq] end

The ? is better at delimiting the line imo

2 Likes

Thank you very much for everyone.
Indeed, I was trying ifelse to make the three-lined code to one.
Everything looks beautiful!