It’s rarely ambiguous. Example:
abs(x) = x<0 ? -x : x
or if you prefer longform function style (I don’t, since I like conciseness):
function abs(x)
return x<0 ? -x : x
end
In contrast, with if usually such a thing would be written:
function abs(x)
if x < 0
return -x
else
return x
end
end
on occasion I’ll make one-liner ifs or do something like this, when it feels right:
abs(x) =
if x < 0; -x
else x
end
The times I run into ambiguity with ? : usually arise from some other expression being combined with the ternary, in which case parentheses become necessary, e.g.:
x + (d > 0 ? d : zero(d))
or, when the returned expression is a range:
true ? (1:2) : (2:3)
but I’ve never seen somebody put return statements inside the ? : sub-expressions, and I don’t see any reason to. Sometimes I might desire to make an assignment in the sub-expression, in which case parenthesizing it has seemed fairly obvious.
By the way, I love one-liner short-circuit && and || for returning from a function early, but for simple ternary expressions like this I prefer the ? : ternary syntax (or sometimes if statements, depending on mood).
On the topic of one-liner if statements (and loops), I’ve adopted a habit of placing a semicolon ; after the condition. Like @bertschi demonstrated, if you don’t, : gets interpreted as a range operator. Additionally there’s this:
julia> if cond (:a) else (:b) end
ERROR: syntax: space before "(" not allowed in "cond (" at REPL[1]:1
julia> if cond [1,2,3] else [4,5,6] end
ERROR: syntax: space before "[" not allowed in "cond [" at REPL[1]:1
julia> var = :x
:( if cond $var=1 else $var=2 end )
ERROR: syntax: unexpected "="
The last one is most likely to happen when interpolating variables into the @btime macro call.
So, since one-liner let, do, and try..catch have trained me to add ; anyway, I do the same after the condition for one-liner if, for, and while to avoid surprise.