Julia Conditionals
Conditional evaluation lets a program take different paths depending on data. Julia offers if/elseif/else blocks, the ternary operator ?:, and short-circuit &&/||.
if, elseif, else
temperature = 23
if temperature > 30
println("Hot")
elseif temperature > 20
println("Pleasant")
elseif temperature > 10
println("Cool")
else
println("Cold")
endPleasant
The conditions are checked from top to bottom, and only the first matching branch runs. elseif and else are optional, and the whole construct ends with a single end. Each condition must evaluate to a Bool.
if is an expression
An if block returns the value of the branch that ran, so you can assign its result. If no branch runs, the value is nothing.
function describe(n)
kind = if n < 0
"negative"
elseif n == 0
"zero"
else
iseven(n) ? "positive even" : "positive odd"
end
return "$n is $kind"
end
for n in (-3, 0, 4, 7)
println(describe(n))
end
r = if false 1 end
println(r === nothing)-3 is negative
0 is zero
4 is positive even
7 is positive odd
true
The ternary operator
condition ? value_if_true : value_if_false is a compact if/else for expressions. The spaces around ? and : are required.
stock = 0
println(stock > 0 ? "In stock" : "Sold out")
grade(score) = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" : "F"
println(grade(95), grade(85), grade(72), grade(40))
println(max(3, 9) == (3 > 9 ? 3 : 9))Sold out
ABCF
true
Chained ternaries read like a table of cases. For anything longer than a few lines, prefer an if block.
Short-circuit conditionals
Because && evaluates its right side only when the left is true, and || only when the left is false, they can replace a one-line if. This idiom is very common for argument checks:
function safe_sqrt(x)
x < 0 && return "cannot take sqrt of $x"
return sqrt(x)
end
println(safe_sqrt(25))
println(safe_sqrt(-1))
function withdraw(balance, amount)
amount <= balance || return "insufficient funds"
return balance - amount
end
println(withdraw(100, 30))
println(withdraw(100, 300))5.0
cannot take sqrt of -1
70
insufficient funds
| Idiom | Meaning |
|---|---|
cond && expr |
if cond then expr |
cond || expr |
unless cond, expr |
Variables introduced in if
if blocks do not create a new scope, so a variable assigned in a branch is visible after the end (as long as that branch ran):
function label(x)
if x > 100
size = "big"
else
size = "small"
end
return size # defined in whichever branch ran
end
println(label(500), " ", label(5))big small
Choosing among many values
Julia has no switch statement. Use if/elseif chains, a dictionary lookup, or multiple dispatch (covered later):
const DAY_NAMES = Dict(1 => "Mon", 2 => "Tue", 3 => "Wed", 4 => "Thu",
5 => "Fri", 6 => "Sat", 7 => "Sun")
day_type(d) = d in (6, 7) ? "weekend" : "weekday"
for d in (3, 6)
println(DAY_NAMES[d], " is a ", day_type(d))
end
println(get(DAY_NAMES, 9, "unknown"))Wed is a weekday
Sat is a weekend
unknown
Test yourself
What does x > 0 ? "pos" : "non-pos" evaluate to when x = 0?
- "pos"
- "non-pos"
- nothing
- an error
What is the value of an if block when no branch runs?
- false
- 0
- nothing
- It throws an error
What does n < 0 && error("negative") do when n = 5?
- Throws the error
- Does nothing and evaluates to false
- Returns 5
- Is a syntax error