Statements
Statements represent a basic mechanism of control flow in TML. TML is a structured imperative language, and supports familiar statement types.
Selection statements
If statement
If statement is used to redirect control flow based on the result of condition expression.
Depending on whether the condition is true or false, main or else branch is chosen.
Condition expressions are evaluated top to bottom.
Only one branch is executed, when the first true condition expression is encountered.
Serial checks can be specified concisely using elseif.
else and elseif branches are optional.
If all checks returned false, else branch is executed, if present.
Condition must be of bool type.
The most general form of the if statement:
if <condition>:
<then-body>
elseif <condition>:
<elseif-body>
else:
<else-body>
end
Example:
if p.multiplication == "Matrix(K*u)":
t.out = p.gain * t.in
elseif p.multiplication == "Const":
t.out = t.in
else:
t.out = 0
end
Iteration statements
For statement
For statement enables iterating over a range of values. Only ranges bounded on both start and end can be used in for statements.
For more details about range expressions, see Range Expressions.
for i = 1:10:2: # start, increment?, end (not included)
#for body
x = i
end
a = [1, 2, 3]
for i = 0:a.len:
#for body
x = i
end
Note
Current implementation allows only iterating over a range. Iterating over tensors will be implemented in the future.
While statement
While statement enables executing instructions in the body as long as the
while condition is true. Condition expression is evaluated before every loop
iteration.
Condition must be of bool type.
while <condition>:
<body>
end
x = 1
while x < 5:
y += 1
end
Return statement
return statement is used to end an execution of a callee function and return
to the caller.
If function is void (i.e. has no return type), return statement is optional
and is used only to prematurely terminate callee execution.
If function is non-void (i.e. has a return type such as a scalar or a tensor),
return statement is mandatory and all paths must have a return statement.
Typing rules for assignment are applied for return expressions
(for more details, see Type system and Broadcasting).
fn test():
x = 0
if x == 1:
return # Return is optional in void functions
end
y = 5
end
fn test() real:
x = 0
if x == 1:
return 1
end
return 1.5
end
fn test() tensor<int, 5>:
x = 0
if x == 1:
return 5 # Broadcasting is automatically applied
end
return [1, 1, 1, 1, 1]
end
Jump statement
TML is a structured language, and only jumps out of the loops are allowed.
Supported jump statements are break and continue.
break- jump out of the closest loopcontinue- jump to the next iteration of the closest loop
break and continue must be enclosed by a loop.
loc_out = 0
for idx = 1:10:
if idx == 0:
continue
elseif idx == 5:
break
end
loc_out += num
end