if

There are other concepts named if. See the entire list.

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 "" 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
User Contributed Notes
0 notes + add a note