if
There are other concepts named if. See the entire list.
if .. else .., branch statement
The if statement introduces a branch block.
For example, using if at script scope:
x = 4
y = 2
d = 0
if x > y
d = x - y
else
d = y - x
// 2
show scalar "|x-y|" with d
The condition must be a scalar boolean. Only the selected branch is compiled and executed, which lets you guard heavy computations or file writes.
table Products = with
[| as Product, as Price |]
[| "shirt", 10.50 |]
[| "pants", 15.00 |]
doExport = any(Products.Price >= 12)
if doExport
write Products as "/sample/products.tsv" with
Product = Products.Product
Price = Products.Price
Statements that introduce tables (table, read) are not allowed inside if
or else blocks. Variables assigned only inside a branch remain scoped to that
branch unless they are assigned in all branches at the same indentation.
Allowed statements inside a branch
- Nested
if/elseblocks. where,keep where,span,keep span.loop,for,each,autodiff,montecarlo.- Assignments like
A = B, includingA = with,where A =, andexpect A =. writestatements.deletestatements (their effect only lasts until the end of the block).constassignments (but the sameconstcannot be assigned in both branches).
Disallowed statements inside a branch
- Table literals (
[| |]),table,read,show. defandschema.importandexport.
Limitations
if / else blocks are not yet supported inside for, each, autodiff, or
montecarlo blocks.
Variable visibility
If a variable is assigned in both branches, it is available after the block. If a variable already exists and only one branch assigns to it, the other branch preserves its prior value.
table T = with
[| as A, as B |]
[| 1, true |]
[| 2, false |]
cond = any(T.B)
T.A = 5
if cond
T.A = 10
// here, T.A is either the original value (5) or 10
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 "" 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 "" with x, y
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)