Hi I’m very new to Julia and I’m given this code in Julia.
r[k] = length(m) > 0 ? median(m) : missing
What does this mean in Julia?
Thanks in advance!
Hi I’m very new to Julia and I’m given this code in Julia.
r[k] = length(m) > 0 ? median(m) : missing
What does this mean in Julia?
Thanks in advance!
It is the same as:
if isempty(m)
r[k] = missing
else
r[k] = median(m)
end
In other words, you store in r[k]
the median of m
collection. However, it might happen that m
has no elements, in which case median is not well defined so instead missing
(signaling missing value) is stored.
Quoting from the Julia manual, at Conditional Evaluation :
The so-called “ternary operator”, ?:
, is closely related to the if
-elseif
-else
syntax, but is used where a conditional choice between single expression values is required, as opposed to conditional execution of longer blocks of code. It gets its name from being the only operator in most languages taking three operands:
a ? b : c
The expression a
, before the ?
, is a condition expression, and the ternary operation evaluates the expression b
, before the :
, if the condition a
is true
or the expression c
, after the :
, if it is false
. Note that the spaces around ?
and :
are mandatory: an expression like a?b:c
is not a valid ternary expression (but a newline is acceptable after both the ?
and the :
).
This works almost identically to the ternary operator in the C programming language.
And a wiki page describing the ternary operator in many different languages ?: - Wikipedia