if
if .. then .. else .., ternary operator
The ternary operator if-then-else takes a Boolean as first argument, and two identically typed values as second and third arguments. The resulting syntax if c then a else b is treated as an expression.
table T = with
[| as A, as B, as C |]
[| 1, 0, true |]
[| 2, 3, false |]
[| 4, 5, false |]
show table "" a1d3 with
T.A
T.B
T.C
if T.C then T.A else T.B
The above code outputs the following table:
| A | B | C | if T.C then T.A else T.B |
|---|---|---|---|
| 1 | 0 | True | 1 |
| 2 | 3 | False | 3 |
| 4 | 5 | False | 5 |
In many languages (C, C++, Java, C#, ..), the ternary operator is written condition ? if_true : if_false.
A multi-line effect can be achieved by indenting the else keywords (relative to the first line), and further indenting the expressions (relative to the if and else keywords):
a = 42
x = if random.binomial(0.5) then
a + 1
else if random.binomial(0.5) then
a + 2
else
a + 3
// 44
show scalar "x" with x
For aesthetic reasons, it is recommended to align the else vertically with the first if, though that is not required. For example, the following code also works:
a = 42
x = if random.binomial(0.5) then
a + 1
else if random.binomial(0.5) then
a + 2
else
a + 3
// 44
show scalar "x" with x
Advanced remark: It is unspecified whether only one or both branches will be evaluated. For example, the following code might or might not raise a division-by-zero warning, but will always print 10:
a = 10
b = 0
// 10
show scalar "Test" with if b != 0 then a / b else a
if .. else .., branch statement
The if statement introduces a branch block within a user-defined function.
def pure mySwap(x: number, y: number) with
a = 0
b = 0
if x > y
a = y
b = x
else if x == y
a = x
b = x
else
a = x
b = y
return (a, b)
x, y = mySwap(4, 2)
// 2, 4
show summary "" a1b1 with x, y
It is also possible to place return statements within the branches.
def pure mySwap(x: number, y: number) with
if x > y
return (y, x)
else if x == y
return (x, x)
else
return (x, y)
x, y = mySwap(4, 2)
// 2, 4
show summary "" a1b1 with x, y
The if statement is not allowed outside the declaration of user-defined functions.
Advanced remark: Unlike the ternary operator, the branch statement guarantees that only one branch will be executed. For example, the following code will never divide by zero:
def pure compute(a: number, b: number) with
if b != 0
return a / b
else
return a
// 10
show scalar "Test" with compute(10, 0)