Julia Language if...else expression


Example

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 form in Julia is actually an expression, and has a value; the value is the expression in tail position (that is, the last expression) on the branch that is taken. Consider the following sample input:

julia> mygcd(0, -10)
10

Here, a is 0 and b is -10. The condition a == 0 is true, so the first branch is taken. The returned value is abs(b) which is 10.

julia> mygcd(2, 3)
1

Here, a is 2 and b is 3. The condition a == 0 is false, so the second branch is taken, and we compute mygcd(b % a, a), which is mygcd(3 % 2, 2). The % operator returns the remainder when 3 is divided by 2, in this case 1. Thus we compute mygcd(1, 2), and this time a is 1 and b is 2. Once again, a == 0 is false, so the second branch is taken, and we compute mygcd(b % a, a), which is mygcd(0, 1). This time, a == 0 at last and so abs(b) is returned, which gives the result 1.