Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia ternary operator without `else`

Consider the ternary operator in Julia

julia> x = 1 ; y = 2

julia> println(x < y ? "less than" : "not less than")
less than

Question: Is there a way to omit the : part of the statement ? Something which would be equivalent to

if condition
    # dosomething
end

without writing that if the condition is not met, nothing should be done.

NB: I researched the answer but nothing came out, even in related questions (1, 2)

like image 389
Joris Limonier Avatar asked Apr 13 '21 14:04

Joris Limonier


2 Answers

Just do:

condition && do_something

For an example:

2 < 3 && println("hello!")

Explanation:

&& is a short-circut operator in Julia. Hence, the second value will be only evaluated when it needs to be evaluated. Hence when the first condition evaluates to false there is no need to evaluate the second part.

Finally, note that you can also use this in an assignment:

julia> x = 2 > 3 && 7
false

julia> x = 2 < 3 && 7
7

This however makes x type unstable so you might want to wrap the right side of the assignment around Int such as x = Int(2 > 3 && 7) than your x will be always an Int.

like image 140
Przemyslaw Szufel Avatar answered Sep 23 '22 23:09

Przemyslaw Szufel


&& is commonly used for this because it is short, but you have to know the trick to read it. I sometimes find it more readable to just use a regular old if statement. In Julia, it need not be across multiple lines if you want to save space.

julia> x = 1; y = 2;

julia> if (x < y) println("less than") end
less than

julia> if (x > y) println("greater than") else println("not greater than") end
not greater than

Note that the parentheses are not required around the conditional in this case; I just add them for clarity. Also, note that I moved println next to the string for clarity, but you can place the whole if statement inside println, as you did in the question, if you prefer.

like image 42
Nathan Boyer Avatar answered Sep 21 '22 23:09

Nathan Boyer