Topic: Expressions

Online Help


Expression blocks


An expression block encloses a list of expressions, divided by semicolons. All expressions can assign to local variables. You can use expression blocks to embed short algorithmic procedures into function definitions, inline loops or any other expressions and expression blocks. There are two types of expression blocks that differ only in the way they are rendered in the output:

$Block{expr1; expr2; expr3; ...} - multiline block of expressions;
$Inline{expr1; expr2; expr3; ...} - inline block of expressions;

As the respective names imply, $Block is rendered on multiple lines so that each expression is placed on a separate line, and for $Inline all expressions are rendered on a single line sequentially from left to right.

You can use expression blocks to create multiline functions when a single expression is not sufficient to evaluate the result. Such is the quadRoots function in the example below that calculates the roots of a quadratic equation, by given coefficients a, b, c and returns them as a vector of two elements [x1; x2].

Code Output
quadRoots(a; b; c) = _
$block{

  D = b^2 - 4*a*c;
  x_1 = (-b - sqrt(D))/(2*a);
  x_2 = (-b + sqrt(D))/(2*a);
  [x_1; x_2];
}
quadRoots(2; 3; -5)

quadRoots ( a; b; c )  = 🞀D = b2 − 4 · a · c
x1 = -b −  D2 · a
x2 = -b +  D2 · a
[x1; x2]

quadRoots  ( 2; 3; -5 )  = [-2.5 1]

 

When you have a $Repeat inline loop you can nest multiple expressions directly inside without enclosing them with a $block/$inline element.

All expressions inside a block or inline loop are compiled, so they are executed very fast. They are evaluated sequentially from left to right and only the last result is returned at the end. However, unlike the standard expressions you cannot see intermediate results and substituted variables. This reduces readability and verifiability of calculations. So, expression blocks should be used only where they are actually needed.

Each variable created by the "=" operator inside a code block of type $block$inline$while and $repeat is local for this block and the nested ones, even if it already exists outside. In this case, the existing variable will not be overwritten and will preserve its original value after the execution of the block. All global and outer scope variables and functions are visible inside the current and inner blocks and accessible for reading.

In general, this is considered a good language design because there are no unpredictable side effects like accidentally changing some global variables just because the names are coincident. However, in certain scenarios, we may need to update global variables deliberately, mostly inside loops. For that purpose, you have to use a special operator "". Unlike "=", it does not create a local variable. Instead, it searches for the innermost existing variable in the current or outer scopes and updates its value. If the variable does not exist, an error is reported.