Joris Limonier
Joris Limonier

Reputation: 817

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)

Upvotes: 7

Views: 1530

Answers (2)

Nathan Boyer
Nathan Boyer

Reputation: 1474

&& 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.

Upvotes: 8

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

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.

Upvotes: 17

Related Questions