Best way for comparisons in one line to avoid undesired effects of operator precedence

I am wondering how to write best a simple

if comparison 
    expression 
else 
    expression
end

in one line.

julia>  if 7+2<10  3 else 0 end
3

works as desired. If the comparison is true, give a value 3 else give a value 0.

But if the value resulting from condition true should be negative = - 3 then the above does not work any more:

julia>  if 7+2<10  -3 else 0 end
0

It is executed as if 7+2<(10 -3) else 0 end and this is not the code I want.

So far understandable to me.
Splitting the code over two lines would help:

julia>   if 7+2<10  
         -3 else 0 end
-3

I am trying to fine ways to write it as oneliner:

julia>  if (7+2<10)  -3 else 0 end
ERROR: TypeError: non-boolean (Int64) used in boolean context

also gives an error.
The versions below give also an errors:

julia> if (7+2<10)  (-3) else 0 end
ERROR: syntax: space before "(" not allowed in "((7 + 2) < 10) (" at REPL[131]:1
julia> if (7+2<10)  (3) else 0 end
ERROR: syntax: space before "(" not allowed in "((7 + 2) < 10) (" at REPL[131]:1

Surprisingly the following works as desired:

julia> if 7+2<10  (-3) else 0 end
julia> if (7+2<10)  3 else 0 end

So I wonder what is the best way to for a “if else end” statement in one line
to clearly separate the condition from the expression if the condition is true.

A ternary operator is also an option.

From my experiments it seems best not to use parentheses in then condition part and use parentheses for the expression part may work.
Like:

if 7+2<10 && 4+1<=8-1  (-3) else 0 end

Is there another way to clearly separate condition part and the expression part in a if then else oneliner?

Two ways:

julia> if 7+2<10; -3 else 0 end
-3

julia> 7+2<10 ? -3 : 0
-3
8 Likes

Thanks a lot!
What does this “;” do? Could you explain more? A semicolon can be used allways to separate parts of code where it is not clear?

No it’s just that A ? B : C is Julia’s cool syntax to say if A then B else C.

[EDIT] Sorry, I misread your semicolon for a colon (you wrote “colon” instead of “semicolon”, which confused me)… In if A; B else C end, the semicolon ; does what you think: it separates the condition A from what to do if A is true.

2 Likes

To complement a little @briochemc comment, in Julia semicolons (outside function calls) and newlines are interchangeable, so if you need a newline anywhere, you may use instead a semicolon in its place.

5 Likes

Thank you very much for your answers. Now I understand it better!