e.g. what does it do here:
pow2(x, n) = n <= 0 ? 1 : x*pow2(x, n-1)
or here
minmax(xx, y) = (y < xx) ? (y, xx) : (xx, y)
If you use the help mode on the REPL by typing ?
you can see the following documentation.
help?> ?
search: ? ?:
a ? b : c
Short form for conditionals; read "if a, evaluate b otherwise evaluate c". Also known as the ternary operator (https://en.wikipedia.org/wiki/%3F:).
This syntax is equivalent to if a; b else c end, but is often used to emphasize the value b-or-c which is being used as part of a larger expression, rather
than the side effects that evaluating b or c may have.
See the manual section on control flow for more details.
Examples
≡≡≡≡≡≡≡≡≡≡
julia> x = 1; y = 2;
julia> x > y ? println("x is larger") : println("y is larger")
y is larger
So basically
pow2(x, n) = n <= 0 ? 1 : x*pow2(x, n-1)
is the same as:
function pow2(x,n)
if n<=0
return 1
else
return x*pow2(x,n-1)
end
end
8 Likes
This is eqivalent to
function minmax(xx, y)
if y < xx
return (y, xx)
else
return (xx, y)
end
end
6 Likes
I love the syntax because it matches how I think about conditional assignment.
In my head “to choose x, ask yourself ‘is y greater than 0?’ if so x should be y, otherwise it should be 0.”
In code:
x = y > 0 ? y : 0
2 Likes
Since it wasn’t mentioned earlier, this is known as the ternary conditional operator and is common across most languages: Ternary conditional operator - Wikipedia
3 Likes