This section covers the if-else statement in Julia and the ternary operator, and contains a short discussion of short-circuit evaluation in Julia.
Julia conditionals are comprised of an
if statement and and optional
else statement, followed by the
end keyword. The
if statement requires a boolean predicate value.
if boolean # do something else # do something else end
if 1 < 2 print("true") else print("false") end
It is also possible to provide
elseif clauses to the conditional to check for mutiple possible outcomes.
number = "three" if number == "one" print(1) elseif number == "two" print(2) elseif number == "three" print(3) elseif number == "four" print(4) else print("not 1, 2, 3, or 4") end
For quick-and-dirty evaluations, Julia provides a ternary operator which is similar to those of many other languages. It uses
? : syntax:
predicate ? value_if_true : value_if_false
For example, you could assign a value based on whether or not some other value is even or odd:
x = 3 y = x % 2 == 0 ? 1 : 0
Finally, Julia short-circuits evaluation of compound expressions using
|| as in most other languages:
- Evaluation of
A && Bstops if
- Evaluation of
A || Bstops if
⊻ requires the left and right predicates to be different, its evaluation cannot be short-circuited.
As a demonstration, consider the conditional below.
B is not defined, but this won’t error because the evaluation will short-circuit upon evaluating
A in each case and thus
B is never evaluated.
A = false if !(A && B) println("&& short-circuited") end A = true if A || B println("|| short-circuited") end
&& short-circuited || short-circuited
Exercise 2.2.1: Write a function
print_name(name::String) which prints out the name
name only if it’s length is greater than 0. If the length is 0, it should print out
"Name string is empty.".
Hint: You can use
length(s) to get the length of a string
Exercise 2.2.2: Following each line below, write the value of
x = 1 < 2 ? 0 : 1 # x = ____ x = x > -1 ? 2 : 0 # x = ____ x = true && false ? 3 : 5 # x = ____ x = x == 5 ? 2 : -1 # x = ____ x = x < 0 ? -1 : 4 # x = ____
Exercise 2.2.3: For each line below, determine whether or not the line will error in evaluation. If a line errors, assume it is not executed. Assume that
A = true,
B = false, and
C = true have already been set.
A && B # Error? ____ A && D # Error? ____ A || C # Error? ____ B && E # Error? ____ C || D # Error? ____ C && (A || B) # Error? ____ B && (A || D) # Error? ____ A && (C && D) # Error? ____ B ⊻ D # Error? ____