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?