Tutorial by Examples

The most common conditional in Julia is the if...else expression. For instance, below we implement the Euclidean algorithm for computing the greatest common divisor, using a conditional to handle the base case: mygcd(a, b) = if a == 0 abs(b) else mygcd(b % a, a) end The if...else for...
name = readline() if startswith(name, "A") println("Your name begins with A.") else println("Your name does not begin with A.") end Any expression, such as the if...else expression, can be put in statement position. This ignores its value but still execu...
Like any other expression, the return value of an if...else expression can be ignored (and hence discarded). This is generally only useful when the body of the expression has side effects, such as writing to a file, mutating variables, or printing to the screen. Furthermore, the else branch of an i...
pushunique!(A, x) = x in A ? A : push!(A, x) The ternary conditional operator is a less wordy if...else expression. The syntax specifically is: [condition] ? [execute if true] : [execute if false] In this example, we add x to the collection A only if x is not already in A. Otherwise, we jus...
For branching The short-circuiting conditional operators && and || can be used as lightweight replacements for the following constructs: x && y is equivalent to x ? y : x x || y is equivalent to x ? x : y One use for short-circuit operators is as a more concise way to test a ...
d = Dates.dayofweek(now()) if d == 7 println("It is Sunday!") elseif d == 6 println("It is Saturday!") elseif d == 5 println("Almost the weekend!") else println("Not the weekend yet...") end Any number of elseif branches may be used...
shift(x) = ifelse(x > 10, x + 1, x - 1) Usage: julia> shift(10) 9 julia> shift(11) 12 julia> shift(-1) -2 The ifelse function will evaluate both branches, even the one that is not selected. This can be useful either when the branches have side effects that must be evaluat...

Page 1 of 1