You are here: Start » Programming Reference » Formulas

# Formulas

## Introduction

A formula block enables to write down operations on basic arithmetic and logic types in a concise textual form. Its main advantage is the ability to simplify programs, in which calculations may require use of a big number of separate filters with simple mathematical functions.

Formula notations consist of a sequence of operators, arguments and functions and are founded on basic rules of mathematical algebra. Their objective in Adaptive Vision Studio is similar to formulas in spreadsheet programs or expressions in popular scripting languages.

A formula block can have any number of inputs and outputs defined by the user. These ports can be of any unrelated types, including various types in one block. Input values are used as arguments (identified by inputs names) in arithmetic formulas. There is a separate formula assigned to each output of a block, the role of such formula is to calculate the value held by given output. Once calculated, a value from output can be used many times in formulas of outputs which are located at a lower position in a block description.

Each of arguments used in formulas has a strictly defined data type, which is known and verified during formula initialization (so called static typing). Types of input arguments arise from explicitly defined block port types. These types are then propagated by operations performed on arguments. Finally, a formula value is converted to the explicitly defined type assigned to a formula output. Compatibility of these types is verified during program initialization (before the first execution of formula block), all incompatibilities are reported as errors.

Formula examples:

outValue = inValue + 10
outValue = inValue1 * 0.3 + inValue2 * 0.7
outValue = (inValue - 1) / 3
outValue = max(inValue1, inValue2) / min(inValue1, inValue2)
outRangePos = (inValue >= -5 and inValue <= 10) ? (inValue - -5) / 15 : Nil
outArea = inBox.Width * inBox.Height


## Data types

Blocks of arithmetic-logic formulas can pass any types from inputs to outputs. The data types mentioned below are recognized by operators and functions available in formulas and therefore they can take part in processing their values.

Data type Description
Integer

Arithmetic type of integral values in the range of -2,147,483,648...2,147,483,647, it can be used with arithmetic and comparison operators.

Integer?
Integer*

Conditional or optional arithmetic type of integral values, it can additionally take value of Nil (empty value).

It can be used everywhere, where the type of Integer is accepted. It (if an operator or a function doesn't assume different behavior) causes that the result of an operation performed on it is also a conditional value. It means that an occurrence of Nil value causes that operation execution is aborted and Nil value is returned as operation result.

Real

Real number (floating-point), it can be used with arithmetic and comparison operators.

Real?
Real*

Conditional or optional real value, it can additionally take value of Nil (empty value).

Similarly to Integer? it can be used everywhere, where the type of Real is accepted causing conditional execution of operators.

Long

Arithmetic type of integral values in the range of -9,223,372,036,854,775,808...9,223,372,036,854,775,807, it can be used with arithmetic and comparison operators.

Long?
Long*

Conditional or optional equivalent of Long type, it can additionally take value of Nil (empty value).

Similarly to Integer? it can be used everywhere, where the type of Long is accepted causing conditional execution of operators.

Double

Double precision floating-point number, it can be used with arithmetic and comparison operators.

Double?
Double*

Conditional or optional equivalent of Double type, it can additionally take value of Nil (empty value).

Similarly to Integer? it can be used everywhere, where the type of Double is accepted causing conditional execution of operators.

Bool

Logic type, takes one of the two values: true or false. It can be used with logic and comparison operators or as a condition argument. It's also a result of comparison operators.

Bool?
Bool*

Conditional or optional logic type, it can additionally take value of Nil (empty value).

It can be used everywhere, where the type of Bool is accepted. It (if an operator or a function doesn't assume different behavior) causes that the result of an operation performed on it is also a conditional value. It means that an occurrence of Nil value causes that operation execution is aborted and Nil value is returned as operation result.

String

Textual type accepting character strings of dynamic length.

Text length (in characters) can be determined using String type built-in .Length property.

String?
String*

Conditional or optional textual type, it can additionally take value of Nil (empty value).

It can be used everywhere, where the type of String is accepted. It (if an operator or a function doesn't assume different behavior) causes that the result of an operation performed on it is also a conditional value. It means that an occurrence of Nil value causes that operation execution is aborted and Nil value is returned as operation result.

enum

Any of the enumeration types declared in the type system. An enumeration type defines a limited group of items which can be assigned to a value of given type. Every one of these items (constants) is identified by a unique name among the given enumeration type (e.g. enumeration type SortingOrder has two possible values: Ascending and Descending).

As part of formulas it is possible to create a value of enumeration type and to compare two values of the same enumeration type.

enum?
enum*

Any conditional or optional enumeration type, instead of a constant, it can additionally take value of Nil (empty value).

structure

Any structure - a composition of a number of values of potentially different types in one object. Within formulas, it is possible to read separately structure elements and to perform further operations on them within their types.

structure?
structure*

Any conditional or optional structure, instead of field composition, it can additionally take value of Nil (empty value).

It is possible to get access to fields of conditional structures on the same basis as in the case of normal structures. However, a field to be read is also of conditional type. Reading fields of a conditional structure of value Nil returns as a result Nil value as well.

<T>Array

Any array of values. Within formulas, it is possible to determine array size, read and perform further operations on array elements.

Array size can be determined by .Count property which is built-in in array types.

<T>Array?
<T>Array*

Any conditional or optional array, instead of elements sequence it can additionally take value of Nil (empty value).

It is possible to read sizes and elements of conditional arrays on the same basis as in the case of normal arrays. In this case, values to be read are also of conditional type. Reading an element from a conditional array of Nil value returns as a result Nil value as well.

## Literal constants

You can place constant values in a formula by writing them down literally in the specified format.

Data type Example
Integer value in decimal notation Integer 0
150
-10000
Long 0L
150L
-10000L
Integer value in hexadecimal notation Integer 0xa1c
0x100
0xFFFF
Long 0xa1cL
0x100L
0xFFFFL
Real value in decimal notation Real 0.0
0.5
100.125
-2.75
Double 0.0d
0.5d
100.125d
-2.75d
Real value in scientific notation Real 1e10
1.5e-3
-5e7
Double 1e10d
1.5e-3d
-5e7d
Text String "Hello world!"
"First line\nSecond line"
"Text with \"quote\" inside."

### Textual constants

Textual constants are a way to insert data of type String into formula. They can be used for example in comparison with input data or in conditional generating of proper text to output of formula block. Textual constants are formatted by placing some text in quotation marks, e.g.: "This is text"; the inner text (without quotation marks) becomes value of a constant.

In case you wish to include in a constant characters unavailable in a formula or characters which are an active part of a formula (e.g. quotation marks), it is necessary to enter the desired character using escape sequence. It consists of backslash character (\) and proper character code (in this case backslash character becomes active and if you wish to enter it as a normal character it requires the use of escape sequence too). It is possible to use the following predefined special characters:

• \n - New line, ASCII: 10
• \r - Carriage return, ASCII: 13
• \t - Horizontal tabulation, ASCII: 9
• \' - Apostrophe, ASCII: 39
• \" - Quotation mark, ASCII: 34
• \\ - Backslash, ASCII: 34
• \v - Vertical tabulation, ASCII: 11
• \a - "Bell", ASCII: 7
• \b - "Backspace", ASCII: 8
• \f - "Form feed", ASCII: 12

Examples:

 "This text \"is quoted\"" "This text\nis in new line" "In Microsoft Windows this text:\r\nis in new line." "c:\\Users\\John\\" 

Other characters can be obtained by entering their ASCII code in hexadecimal format, by \x?? sequence, e.g.: "send \x06 ok" formats text containing a character of value 6 in ASCII code, and "\xce" formats a character of value 206 in ASCII code (hex: ce).

## Predefined constant values

As part of formula, it is possible to obtain access to one of the below-mentioned predefined constant values. In order to use a constant value as operation argument, it is required to enter the name of this constant value.

Name Data type Description
true Bool

Positive logic value.

false Bool

Negative logic value.

Nil Null

Special value of conditional and optional types, it represents an empty value (no value).

This constant doesn't has its own data type (it is represented by the special type of "Null"). Its type is automatically converted to conditional types as part of executed operations.

pi Real

Real value, it is the approximation of π mathematical constant.

e Real

Real value, it is the approximation of e mathematical constant.

inf Real

Represents positive infinity. It is a special value of type Real that is greater than any other value possible to be represented by the type Real. Note that negative infinity can be achieved by "-inf" notation.

### Enumeration constants

There are enumeration constants defined in the type system. They have their own types and among these types a given constant chooses one of a few possibilities. E.g. a filter for array sorting takes a parameter which defines the order of sorting. This parameter is of "SortingOrder" enumeration type. As part of this type, you can choose one of two possibilities identified by "Ascending" and "Descending" constants.

As part of formulas, it is possible to enter any enumeration constant into formula using the following syntax:

<enum name>.<item name>

Full name of a constant used in a formula consists of enumeration type name, of a dot and of name of one of the possible options available for a given type, e.g.:

 SortingOrder.Descending BayerType.BG GradientOperator.Gauss 

## Arithmetic conversions

Binary arithmetic operators are executed as part of one defined common type. In case when the types of both arguments are not identical, an attempt to convert them to one common type is performed, on this type the operation is then executed. Such conversion is called arithmetic conversion and when it's possible to carry it out, the types of arguments are called compatible.

Arithmetic conversion is performed as part of the following principles:

Conditions Performed conversions
Two different numeric types. The argument of type with smaller range or precision is converted to the type of second argument (with greater range or precision). Possible argument type conversions includes: Integer to Real, Integer to Long, Integer to Double and Real to Double. The same principle is used in case of conditional counterparts of mentioned types.
One of the types is conditional. The second type is converted to conditional type.
Two different conditional types. Arithmetic conversion is performed as part of types on which arguments conditional types are based. As the result, the types remain conditional.
One of the arguments is Nil. The second argument is converted to conditional type (if it's not already conditional), Nil value is converted to the conditional type of the second argument.

## Automatic implicit conversions

When some operation requires an argument of certain type and, instead of it, an argument of different type is used, implicit conversion of such argument type is attempted using the below-mentioned principles.

Conversion Description
Integer → Real
Integer → Double

Conversion of integer to floating-point value. As part of such conversion loss of precision may occur. As the result of it, instead of accurate number representation, an approximated floating-point value is returned.

Such conversion is also possible when it comes to conditional counterparts of given types.

Integer → Long
Real → Double

Conversion to equivalent type with greater range or precision. No data is lost as a result of such conversion.

Such conversion is also possible when it comes to conditional counterparts of given types.

T → T?

Assigning conditionality. Any non-conditional type can be converted to its conditional counterpart.

Nil → T?

Assigning type to a Nil value. Nil value can be converted to any conditional type. As the result of it, you get an empty value of given type.

T* → T?

As part of formulas, optional and conditional types are handled the same way (in formulas there is no defined reaction for automatic values, they only pass data). If given operation requires argument of conditional type, then it also can, basing on the same principles, take argument of optional type.

## Operators

As part of formulas, it is possible to use the following operators:

 Negation operator: - Identity operator: + Two's complement: ~ Logic negation: not Multiplicative operators: * / div mod Additive operators: + - Bit shift: >> << Bitwise operators: & | ^ Logic operators: and or xor Comparison operator: < <= > >= Equality testing: == <> Conditional operator: if-then-else  ?: Merge with default value: ?? Function call: function() Field read: . Array element read: [] Array creation operator: {} Previous value of output: prev()

### Unary operators

##### Negation operator (-)
- expression

Data types: Integer, Real, Long, Double, Vector2D, Vector3D

Returns numeric value with negated sign or vector with same length but opposite direction.

##### Identity operator (+)
+ expression

Data types: Integer, Real, Long, Double, Vector2D, Vector3D

Returns value without any changes.

##### Two's complement operator (~)
~ expression

Data types: Integer, Long

Returns integer value with negated bits (binary complement).

##### Logic negation operator (not)
not expression

Data types: Bool

Returns logic value of an opposite state.

### Binary operators

##### Multiplication operator (*)
expression * expression

Data types: Integer, Real, Long, Double, Vector2D, Vector3D

Returns product of two numeric arguments, element-by-element product of two vectors, or vector scaled by factor.

##### Real division operator (/)
expression / expression

Data types: Real, Double, Vector2D, Vector3D

Returns quotient of two real numbers, element-by-element quotient of two vectors, or vector which length was divided by scalar factor.

##### Integer division operator (div)
expression div expression

Data types: Integer, Long

Returns quotient of two integer numbers without residue. A Domain Error appears during program runtime when second argument is equal to zero.

##### Modulo operator (mod)
expression mod expression

Data types: Integer, Long

Returns residue from division of two integer numbers. A Domain Error appears during program runtime when second argument is equal to zero.

##### Addition operator (+)
expression + expression

Data types:

 Integer + Integer → Integer Long + Long → Long Real + Real → Real Double + Double → Double Vector2D + Vector2D → Vector2D Point2D + Vector2D → Point2D Vector3D + Vector3D → Vector3D Point3D + Vector3D → Point3D String + String → String

Returns sum of two numeric values, sum of two vectors or moves a point by a vector.

In case of using it with String type, it performs text concatenation and returns connected string.

##### Subtraction operator (-)
expression - expression

Data types:

 Integer - Integer → Integer Long - Long → Long Real - Real → Real Double - Double → Double Vector2D - Vector2D → Vector2D Point2D - Vector2D → Point2D Vector3D - Vector3D → Vector3D Point3D - Vector3D → Point3D

Returns difference of two numeric values, subtracts two vectors or moves a point backwards by a vector.

##### Bit right-shift (>>)
expression >> expression

Data types: Integer, Long

Returns value of the first argument, in which bits of its binary representation have been shifted right (in the direction of the less meaningful bits) by the number of positions defined by the second argument. After the shift, bits which exceed the type range on the right side are ignored. The lacking bits on the left side are filled in with zeros.

A Domain Error appears during program runtime when second argument is negative. In case of shift value larger than 31 for Integer type, or larger than 63 for Long type, the value of 0 will be returned.

##### Bit left-shift (<<)
expression << expression

Data types: Integer, Long

Returns value of the first argument, in which bits of its binary representation have been shifted left (in the direction of the more meaningful bits) by the number of positions defined by the second argument. After the shift, bits which exceed the type range on the left side are ignored. The lacking bits on the right side are filled in with zeros.

A Domain Error appears during program runtime when second argument is negative. In case of shift value larger than 31 for Integer type, or larger than 63 for Long type, the value of 0 will be returned.

##### Bitwise AND (&)
expression & expression

Data types: Integer, Long

Returns value of bitwise product of two integer numbers. This operator compares separately each pair of corresponding bits of two arguments. If values of both bits equal 1, then the result bit also equals 1. If value of at least one bit equals 0, then the result bit equals 0.

##### Bitwise OR (|)
expression | expression

Data types: Integer, Long

Returns value of bitwise sum of two integer numbers. This operator compares separately each pair of corresponding bits of two arguments. If value of at least one bit equals 1, the result bit also equals 1. If values of both bits equal 0, then the result bit equals 0.

##### Bitwise exclusive OR (^)
expression ^ expression

Data types: Integer, Long

Returns value of bitwise exclusive sum of two integer numbers. This operator compares separately each pair of corresponding bits of two arguments. If two bits are equal, the result bit equals 0. If two bits are not equal, then the result equals 1.

##### Logic AND (and)
expression and expression

Data types: Bool

This operator merges two logic arguments. If both arguments equal true, then the result also equals true. If at least one of the arguments equals false, then the result equals false.

##### Logic OR (or)
expression or expression

Data types: Bool

This operator merges two logic arguments. If at least one of the arguments equals true, then the result equals true. If both arguments equal false, then the result also equals false.

##### Logic exclusive OR (xor)
expression xor expression

Data types: Bool

This operator merges two logic arguments. If the arguments are unequal, then the result equals true. If the arguments are equal, then the result equals false.

##### Less than (<)
expression < expression

Data types: Integer, Real, Long, Double, String

Result type: Bool

This operator compares two values. It returns value of true only if value of the first argument is smaller than value of the second argument.

In case of using it with String type, the operator performs lexicographic text comparison.

##### Less than or equal to (<=)
expression <= expression

Data types: Integer, Real, Long, Double, String

Result type: Bool

This operator compares two values. It returns value of true only if value of the first argument is smaller than or equal to value of the second argument.

In case of using it with String type, the operator performs lexicographic text comparison.

##### Greater than (>)
expression > expression

Data types: Integer, Real, Long, Double, String

Result type: Bool

This operator compares two values. It returns value of true only if value of the first argument is larger than value of the second argument.

In case of using it with String type, the operator performs lexicographic text comparison.

##### Greater than or equal to (>=)
expression >= expression

Data types: Integer, Real, Long, Double, String

Result type: Bool

This operator compares two values. It returns value of true only if value of the first argument is larger than or equal to value of the second argument.

In case of using it with String type, the operator performs lexicographic text comparison.

##### Equality test (==)
expression == expression

Data types: any compatible types

Result type: Bool

This operator compares two arguments. If their values are equal, it returns value of true, otherwise it returns value of false. It's possible to determine the equality not only between compatible primitive types, but also between objects of any two same types (e.g. structures).

Please note that comparing values of type Real or Double (or structures with those types) may be tricky. It is caused by the fact that very small (unnoticeable) differences in values of such types may lead to unpredictable negative results of the comparison.

The operator treats conditional values in a special way. An occurrence of conditional type in one or both arguments doesn't cause that the whole operator is executed conditionally. Empty values of conditional types take part in comparisons too. It is also possible to determine if an argument carries a conditional empty value by comparing it to Nil constant.

This operator never returns conditional type.

##### Inequality test (<>)
expression <> expression

Data types: any compatible types

Result type: Bool

This operator performs an identical comparison to == operator, but it returns an opposite value (true, when arguments are not equal).

### Special operators

##### Conditional operator (if-then-else, ?:)
 if condition_expression then expression_1 else expression_2 if   condition_expression_1 then expression_1 elif condition_expression_2 then expression_2  (...) elif condition_expression_n then expression_n_minus_1 else expression_n condition_expression ? expression_1 : expression_2 

Data types:

• condition_expression_x: Bool
• expression_1, expression_2, ..., expression_n: any compatible types

This operator conditionally chooses and returns one of two or more values.

 if condition_expression then expression_1 else expression_2 

The first operand, in this case condition_expression, is a condition value of Bool data type. Depending on whether condition_expression equals True or False, it returns either expression_1 (when True) or expression_2 (when False).

 if   condition_expression_1 then expression_1 elif condition_expression_2 then expression_2  (...) elif condition_expression_n then expression_n_minus_1 else expression_n 

When connecting multiple conditions in a row, the program checks whether any of the consecutive conditions is met. The original condition uses the clause if...then, all the following ones use the clause elif...then. Should any of these multiple conditions be found to be True, then the corresponding expression is returned. However, after both the if...then clause and all the elif...then clauses are found to be False, the operator else calls the one expression that must be returned instead.

The operator treats conditional values in a special way. An occurrence of conditional type only in case of the first operand (condition value) causes the whole operator to be executed conditionally. Conditional types in operands of values to choose from do not make any changes in operator execution. Values of these operands are always passed in the same way that operation results are (also in case of an empty value).

The operator result type is determined by combining types of values to choose from (by converting one type to another or by converting two types into yet another common result type), according to the principles of arithmetic conversions. Such types can be changed to a conditional type in case of operator conditional execution.

##### Merge with default (??)
expression ?? expression

Data types: any compatible types

This operator requires that the first argument is of conditional type. If the first argument returns a non-empty value, then this value becomes the result of the whole operation. If the first argument returns an empty value (Nil), then the value of the second argument becomes the result of the whole operation.

Operation result type is the type proceeding from combining types of two arguments, but with a modified conditionality. If the second argument is of non-conditional type, then the result of the whole operation is non-conditional too. If the second argument is of conditional type, then the result of the whole operation is conditional.

This operator can be used for choosing an alternative value basing on a condition of the empty first argument.

The operator is called merging with default value, because it allows removing conditionality from an argument and replacing its empty value with a default value. In order to do this, the second argument cannot be of conditional type.

This operator is intended to handle conditional types, it means that the operator itself is never executed conditionally.

##### Function call (function())
 function(arg_1, arg_2, ..., arg_n) function<type_name>(arg_1, arg_2, ..., arg_n) 

Function call is performed by entering function name and a follow-up list of arguments in brackets. Required data types depend on the called function. For functions with generic type it is also optionally possible to explicitly specify the generic type in angular brackets directly after the function name.

See: Functions

##### Field read (.)
expression.name

This operator is used to read a single structure field or a property supported by an object. Operation result type is compatible with the type of the field which is read.

Any structure (from which a field of any type is read) can be passed as an argument.

name determines name of a field (or property), which should be read.

##### Object function call (.function())
expression.function(arg_1, arg_2, ..., arg_n)

This construction is intended to call a function provided by an object (defined by data type of expression object).

Access to this function is provided (similar to field read operator) by entering a dot sign and the function name after an argument. After the function name a list of function arguments should be entered in round brackets. The required data types depend on the function which is called.

##### Array element read ([])
expression[indexer]

Data types:

 Array[i] → Path[i] → Point2D

This operator is used to read a single element from an array or a single point from a Path object. Operator result type is equal to the array elements type. An indexer has to be an argument of type Integer, its value points to an element to be read (value of 0 indicates the first array element). If an indexer returns a value pointing out of 0...ArrayLength-1 range, then the operator causes that a Domain Error appears during program runtime.

##### Array creation ({})
{item_1, item_2, ..., item_n}

Creates an array out of the specified elements.

Provided elements must be of the same data type or be convertible to the same type using the rules of arithmetic conversions. Returned value is of type TArray, where T is a common type of specified elements.

Operator requires to provide at least one item. At least one of the provided items must be different than constant Nil (have non-null type).

##### Previous value of output (prev())
prev(outputName, defaultValue)prev(outputName)

This operator is used to read the value of a formula block output from the previous iteration of a task loop, inside which the formula block is instantiated. This operator takes an identifier as its first argument - the name of the formula block output. Any output of the parent formula block can be used, including the current formula output and outputs of formulas defined below the current one.

Second argument of the operator defines a default value and can accept any expression.

The purpose of this operator is to create an aggregate or sequence generating formula. In the first iteration of a task, this operator returns the default value (defined by the second argument). In each subsequent task iteration the operator returns the value previously computed by the referenced formula output (defined by the first argument).

Operator result type is determined by combining types of referenced output and default value argument, according to the principles of arithmetic conversions.

Second argument of the operator can be omitted. In such situation Nil is used as the default value and the result type is a conditional equivalent of the accessed output type. You can use the merge with default (??) operator to handle a Nil value.

## Operator precedence

In case of using more than one operator in the surrounding of the same argument, the precedence of executing these operators depends on their priorities. In the first instance, operators with the highest priority are executed. In case of binary operators with equal priorities, the operators are executed one after another from left to right, e.g.:

A + B * C / D

In the first instance, arguments B and C are multiplied (multiplication has higher priority than addition and, in this case, is located left from division operator which has the same priority). Multiplication result is divided by D (going from left to right), and then the quotient is added to A.

Unary operators, which are always in form of prefixes, are executed from the closest operator to an argument to the furthest one, that is from right to left.

Ternary conditional operators are executed in order from right to left. It enables nesting conditions as part of other conditional operators arguments.

Order of operators execution can be changed by placing nested parts of formulas in brackets, e.g.:

(A + B) * (C / D)

In this case, addition and division are executed in the first instance, then their results are multiplied.

#### Operator priorities

#OperatorDescription
1 []Array element read
()Function call
.Structure field read
.name()Object function call
2 +Identity
-Negation
~Bitwise negation
notLogic negation
3 * / div modMultiplicative operators
4 + -Additive operators
5 >> <<Bit shift
6& Bitwise operators
7^
8|
9 < <= > >=Values comparison
10 ==Equality test
<>Inequality tests
11and Logic operators
12xor
13or
14 ??Merge with default value
15 ?: Conditional operator
16 if-then-else

A lower number means higher priority and earlier execution of operator.

## Functions

As part of formulas, you can use one of the functions listed below by using a function call operator. Each function has its own requirements defined regarding the number and types of individual arguments. Functions with the same names can accept different sets of parameter types, on which the returned value type depends. Each of the functions listed below has its possible signatures defined in form of descriptions of parameters data types and returned value types resulting from them, e.g.:

Real foo( Integer value1, Real value2 )

This signature describes the "foo" function, which requires two arguments, the first of type Integer and the second of type Real. The function returns a value of type Real. Such function can be used in a formula in the following way:

outValue = foo(10, inValue / 2) + 100

Arguments passed to a function don't have to exactly match a given signature. In such case, the best fitting function version is chosen. Then an attempt to convert argument types to a form expected by the function is performed (according to the principles of implicit conversions). If choosing a proper function version for argument types is not possible or, if it's not possible to convert one or more arguments to required types, then program initialization ends up with an error of incorrect function parameters set.

A conditional or optional type can be used as an argument of each function. In such case, if function signature doesn't assume some special use of conditional types, the entire function call is performed conditionally. A returned value is then also of a conditional type, an occurrence of Nil value among function arguments results in returning Nil value as function result.

#### Generic functions

Some functions accept arguments with so called generic type, where the type is only partially defined and the function is able to adapt to the actual type required. Such functions are designated with "<T>" symbol in their signatures, e.g. function minElement:

<T> minElement( <T>Array items, RealArray values )

This function is designated to process arrays with elements of arbitrary type. Its first argument accepts an array based on its generic type. A value of its generic type is also returned as a result. Generic functions can have only one generic type argument (common for all arguments and return value).

Generic functions can be called in the same way as regular functions. In such case the generic type of the function will be deduced automatically based on the type of specified arguments:

outMinElement = minElement(inBoxArrays, inValuesArrays)

In this example the value on input inBoxArrays is of type BoxArray, so the return type of the functions is Box.

In situations where the generic type cannot be deduced automatically, or needs to be changed from the automatically deduced one, it is possible to specify it explicitly, e.g. in this call of array function:

outNilsArray = array<Box?>(4, Nil)

an array of type Box?Array is created, containing four Nils.

### Mathematical functions

##### sin
Real sin( Real )Double sin( Double )

Returns an approximation of the sine trigonometric function. It takes an angle measured in degrees as its argument.

##### cos
Real cos( Real )Double cos( Double )

Returns an approximation of the cosine trigonometric function. It takes an angle measured in degrees as its argument.

##### tan
Real tan( Real )Double tan( Double )

Returns an approximation of the tangent trigonometric function. It takes an angle measured in degrees as its argument.

##### asin
Real asin( Real )Double asin( Double )

Returns an approximation of the inverse sine trigonometric function. It returns an angle measured in degrees.

##### acos
Real acos( Real )Double acos( Double )

Returns an approximation of the inverse cosine trigonometric function. It returns an angle measured in degrees.

##### atan
Real atan( Real )Double atan( Double )

Returns an approximation of the inverse tangent trigonometric function. It returns an angle measured in degrees.

##### exp
Real exp( Real )Double exp( Double )

Returns an approximated value of the e mathematical constant raised to the power of function argument: exp(x) = ex

##### ln
Real ln( Real )Double ln( Double )

Returns an approximation of natural logarithm of its argument: ln(x) = loge(x)

##### log
Real log( Real )Double log( Double )

Returns an approximation of decimal logarithm of its argument: log(x) = log10(x)

##### log2
Real log2( Real )Double log2( Double )

Returns an approximation of binary logarithm of its argument: log2(x) = log2(x)

##### sqrt
Real sqrt( Real )Double sqrt( Double )

Returns the square root of its argument: sqrt(x) = ²√x

##### floor
Real floor( Real )Double floor( Double )

Rounds an argument down, to an integer number not larger than the argument.

##### ceil
Real ceil( Real )Double ceil( Double )

Rounds an argument up, to an integer number not lesser than the argument.

##### round
Real round( Real, [Integer] )Double round( Double, [Integer] )

Rounds an argument to the closest value with a strictly defined number of decimal places. The first function argument is a real number to be rounded. The second argument is an optional integer number, defining to which decimal place the real number should be rounded. Skipping this argument effects in rounding the first argument to an integer number.

Examples:

 round(1.24873, 2) → 1.25 round(1.34991, 1) → 1.3 round(2.9812) → 3.0 
##### abs
Real abs( Real )Integer abs( Integer ) Double abs( Double )Long abs( Long )

Returns the absolute value of an argument (removes its sign).

##### pow
Real pow( Real, Integer )Real pow( Real, Real ) Double pow( Double, Integer )Double pow( Double, Double )

Raises the first argument to the power of the second argument. Returns the result as a real number: pow(x, y) = xy

##### square
Real square( Real )Double square( Double )

Raises the argument to the power of two: square(x) = x².

##### hypot
 Real hypot( Real a, Real b ) Double hypot( Double a, Double b ) 

Calculates and returns the result of the formula: hypot(a, b) = √a² + b²

##### clamp
 Integer clamp( Integer value, Integer min, Integer max ) Real clamp( Real value, Real min, Real max ) Long clamp( Long value, Long min, Long max ) Double clamp( Double value, Double min, Double max ) 

Limits the specified value (first argument) to the range defined by min and max arguments. Return value is unchanged when it fits in the range. Function returns the min argument when the value is below the range and the max argument when the value is above the range.

##### lerp
 Integer lerp( Integer a, Integer b, Real lambda ) Real lerp( Real a, Real b, Real lambda ) Long lerp( Long a, Long b, Real lambda ) Double lerp( Double a, Double b, Double lambda ) Point2D lerp( Point2D a, Point2D b, Real lambda ) 

Computes a linear interpolation between two numeric values or 2D points. Point of interpolation is defined by the third argument of type Real in the range from 0.0 to 1.0 (0.0 for value equal to a, 1.0 for value equal to b).

### Type conversion functions

##### integer
Integer integer( Real )Integer integer( Double ) Integer integer( Long )

Converts an argument to Integer type by cutting off its fractional part or ignoring most significant part of integer value.

##### real
Real real( Integer )Real real( Long ) Real real( Double )

Converts an argument to Real type.

##### long
Long long( Real )Long long( Double ) Long long( integer )

Converts an argument to Long type (cuts off fractional part of floating-point values).

##### double
Double double( Integer )Double double( Long ) Double double( Real )

Converts an argument to Double type.

##### toString
 String toString( Bool ) String toString( Integer ) String toString( Real ) String toString( Long ) String toString( Double ) 

Converts the argument to readable textual form.

### Statistic and array processing functions

##### min
 Integer min( Integer, ..., Integer ) Real min( Real, ..., Real ) Long min( Long, ..., Long ) Double min( Double, ..., Double ) Integer min( IntegerArray ) Real min( RealArray ) Long min( LongArray ) Double min( DoubleArray ) 

Returns the smallest of input values. This function can take from two to four primitive numeric arguments, from which it chooses the smallest value or an array of primitive numeric values, in which the smallest value is searched for. In case of an attempt to search for a value in an empty array, an operation runtime error is reported.

##### max
 Integer max( Integer, ..., Integer ) Real max( Real, ..., Real ) Long max( Long,..., Long ) Double max( Double, ..., Double ) Integer max( IntegerArray ) Real max( RealArray ) Long max( LongArray ) Double max( DoubleArray ) 

Returns the largest of input values. This function can take from two to four primitive numeric arguments, from which it chooses the largest value or an array of primitive numeric values, in which the largest value is searched for. In case of an attempt to search for a value in an empty array, an operation runtime error is reported.

##### indexOfMin
 Integer indexOfMin( IntegerArray ) Integer indexOfMin( RealArray ) Integer indexOfMin( LongArray ) Integer indexOfMin( DoubleArray ) 

Returns the (zero based) index of the smallest of the values in the input array. When multiple items in the array match the condition the index of the first one is returned. In case of an attempt to search for a value in an empty array, an operation runtime error is reported.

##### indexOfMax
 Integer indexOfMax( IntegerArray ) Integer indexOfMax( RealArray ) Integer indexOfMax( LongArray ) Integer indexOfMax( DoubleArray ) 

Returns the (zero based) index of the largest of the values in the input array. When multiple items in the array match the condition the index of the first one is returned. In case of an attempt to search for a value in an empty array, an operation runtime error is reported.

##### avg
 Integer avg( Integer, Integer ) Real avg( Real, Real ) Long avg( Long, Long ) Double avg( Double, Double ) Point2D avg( Point2D, Point2D ) Point3D avg( Point3D, Point3D ) Integer avg( IntegerArray ) Real avg( RealArray ) Long avg( LongArray ) Double avg( DoubleArray ) Point2D avg( Point2DArray ) Point3D avg( Point3DArray ) 

Computes the arithmetic mean of input numeric values or a middle point (center of mass) of input geometric points. This function can take two arguments, which are averaged or an array of values, which is averaged altogether. In case of an attempt to enter an empty array, an operation runtime error is reported.

##### sum
 Integer sum( IntegerArray ) Real sum( RealArray ) Long sum( LongArray ) Double sum( DoubleArray ) 

Returns the sum of input values. This function can take an array of primitive numeric values, which will be summed altogether. In case of entering an empty array, the value of 0 will be returned.

Note: in case of summing large values or a big number of real arguments, it's possible to partially lose the result precision and, due to this, to mangle the final result. In case of summing integer numbers of too large values, the result may not fit in the allowed data type range.

##### product
 Integer product( IntegerArray ) Real product( RealArray ) Long product( LongArray ) Double product( DoubleArray ) 

Returns the product of entered values. This function can take an array of primitive numeric values, which all will be multiplied. In case of entering an empty array, the value of 1 will be returned.

Note: in case of multiplying large values or a big number of real arguments, it's possible to partially lose the result precision and, due to this, to mangle the final result. In case of multiplying integer numbers of too large values, the result may not fit in the allowed data type range.

##### variance
 Real variance( RealArray ) Double variance( DoubleArray ) 

Computes statistic variance from a set of numbers provided as an array in the argument. Result is computed using the formula: 1n∑(x - xi)2. In case of an attempt to enter an empty array, a domain error is reported.

##### stdDev
 Real stdDev( RealArray ) Double stdDev( DoubleArray ) 

Computes statistic standard deviation from a set of numbers provided as an array in the argument. Result is equal to a square root of variance described above. In case of an attempt to enter an empty array, a domain error is reported.

##### median
 Integer median( IntegerArray ) Real median( RealArray ) Long median( LongArray ) Double median( DoubleArray ) 

Returns the median value from a set of numbers provided as an array in the argument. In case of an attempt to enter an empty array, a domain error is reported.

##### nthValue
 Integer nthValue( IntegerArray, Integer n ) Real nthValue( RealArray, Integer n ) Long nthValue( LongArray, Integer n ) Double nthValue( DoubleArray , Integer n) 

Returns the n-th value in sorted order from a set of numbers provided as an array in the argument. The zero-based index n, of type Integer, is provided as the second argument. In case of an attempt to enter an empty array, a domain error is reported.

##### quantile
 Integer quantile( IntegerArray, Real point ) Real quantile( RealArray, Real point ) Long quantile( LongArray, Real point ) Double quantile( DoubleArray , Real point ) 

Returns the specified quantile from a set of numbers provided as an array in the argument. In case of an attempt to enter an empty array, a domain error is reported.

##### all
Bool all( BoolArray predicates )

This function takes an array of logical values and returns True when all elements in the array are equal to True. In case of entering an empty array, the value of True will be returned.

##### any
Bool any( BoolArray predicates )

This function takes an array of logical values and returns True when at least one element in the array equals True. In case of entering an empty array, the value of False will be returned.

##### count
 Integer count( BoolArray predicates ) Integer count( <T>Array items, <T> value ) 

First variant of this function takes an array of logical values and returns the number of items equal to True.

Second variant takes an array of items and counts the number of elements in that array that are equal to the value given in the second argument.

##### contains
Bool contains( <T>Array items, <T> value )

Checks if the specified array contains a value.

Returns the value of True when the array given in the first argument contains at least one instance of the value from the second argument.

##### findFirst
Integer? findFirst( <T>Array items, <T> value )

Searches the specified array for instances equal to the given value and return the zero based index of the first found item (closest to the beginning of the array). Returns Nil when no items were found.

##### findLast
Integer? findLast( <T>Array items, <T> value )

Searches the specified array for instances equal to the given value and return the zero based index of the last found item (closest to the end of the array). Returns Nil when no items were found.

##### findAll
IntegerArray findAll( <T>Array items, <T> value )

Searches the specified array for instances equal to the given value and return an array of zero based indices of all found items. Returns an empty array when no items were found.

##### minElement
<T> minElement( <T>Array items, RealArray values )

Returns an array element that corresponds to the smallest value in the array of values. When input array sizes does not match or when empty arrays are provided, a domain error is reported.

##### maxElement
<T> maxElement( <T>Array items, RealArray values )

Returns an array element that corresponds to the biggest value in the array of values. When input array sizes does not match or when empty arrays are provided, a domain error is reported.

##### removeNils
<T>Array removeNils( <T>?Array items )

Removes all Nil elements from an array. Returns a new array with simplified type.

##### withoutNils
<T>Array? withoutNils( <T>?Array items )

Returns the source array only when it does not contains any Nil values.

This function accepts an array with conditional items (<T>?Array) and returns a conditional array (<T>Array?). When at least one item in the source array is equal to Nil the source array is discarded and Nil is returned, otherwise the source array is returned with simplified type.

##### flatten
<T>Array flatten( <T>ArrayArray items )

Takes an array of arrays, and concatenates all nested arrays creating a single one-dimensional array containing all individual elements.

##### select
<T>Array select( <T>Array items, BoolArray predicates )

Selects the elements from the array of items for which the associated predicate is True.

Arrays of items and predicates must have the same number of elements. This function returns a new array composed out of the elements from the items array, in order, for which the elements of the predicates array are equal True.

##### crop
<T>Array crop( <T>Array items, Integer start, Integer length )

Selects a continuous subsequence of array elements.

When the specified range spans beyond the source array only the elements intersecting with the requested range are selected (in such case the function will return less than length elements).

##### trimStart
 <T>Array trimStart( <T>Array items ) <T>Array trimStart( <T>Array items, Integer count ) 

Removes count elements from the beginning of the array. By default (when the argument count is omitted) removes a single element. When count is larger than the size of the array an empty array is returned.

##### trimEnd
 <T>Array trimEnd( <T>Array items ) <T>Array trimEnd( <T>Array items, Integer count ) 

Removes count elements from the end of the array. By default (when the argument count is omitted) removes a single element. When count is larger than the size of the array an empty array is returned.

##### rotate (array)
 <T>Array rotate( <T>Array items ) <T>Array rotate( <T>Array items, Integer steps ) 

Rotates the elements from the specified array by steps places. Rotates right (towards larger indexes) when the steps value is positive, and left (towards lower indexes) when the steps value is negative. By default (when the steps argument is skipped) rotates right by one place.

Rotation operation means that all elements are shifted along the array positions, and the elements that are shifted beyond the end of the array are placed back at the beginning.

##### pick
<T>Array pick( <T>Array items, Integer start, Integer step, Integer count )

Picks items from an array at equal spacing.

This function will pick elements from the source array, starting at the start position, and moving forward by a step amount of elements count times. When the specified range spans beyond the source array only the elements intersecting with the requested range are selected (in such case the function will return less than count elements).

The value specified as step must be greater that zero.

##### sequence
 IntegerArray sequence( Integer start, Integer count ) IntegerArray sequence( Integer start, Integer count, Integer step ) RealArray sequence( Real start, Integer count ) RealArray sequence( Real start, Integer count, Real step ) 

Creates an array of count numbers, starting from the value provided in start argument and incrementing the value of each item by the value of step (or 1 when step is not specified).

##### array
<T>Array array( Integer count, <T> item )

Creates a uniform array with count items by repeating the value of item.

##### createArray
 <T>Array createArray( <T> arg1, <T> arg2, ..., <T> argN ) 

Creates an array out of arbitrary number of elements provided in the arguments.

This is basically an equivalent of array creation operator ({}) in function form, allowing for explicit item type specification and empty array creation.

##### join
 <T>Array join( <T>[Array] arg1, <T>[Array] arg2, ..., <T>[Array] argN ) 

Joins an arbitrary (at least two) number of arrays and/or scalar values into a single array. Returns a uniform array with elements in the same order as specified in the function arguments.

### Geometry processing functions

##### angleNorm
Real angleNorm( Real angle, Real cycle )

Normalizes a given angle (or other cyclic value) to the range [0...cycle). cycle must be a positive value (usually 180 or 360, but any greater than zero value is acceptable).

##### angleTurn
Real angleTurn( Real startAngle, Real endAngle, Real cycle )

Calculates a directional difference between two given angles.

Assuming that startAngle and endAngle are cyclic values in the range [0...cycle), this function is calculating the shortest angular difference between them, returning positive values for a forward angle (from startAngle to endAngle), and a negative value for a backward angle. cycle must be a positive value.

##### angleDiff
Real angleDiff( Real angle1, Real angle2, Real cycle )

Calculates an absolute difference between two given angles.

Assuming that given angles are cyclic values in the range [0...cycle), this function is calculating the shortest absolute angular difference between them. Returned value is non-negative. cycle must be a positive value.

##### distance
 Real distance( Point2D, Point2D ) Real distance( Point2D, Segment2D ) Real distance( Point2D, Line2D ) Real distance( Point3D, Point3D ) Real distance( Point3D, Segment3D ) Real distance( Point3D, Line3D ) Real distance( Point3D, Plane3D ) 

Calculates the distance between a point and the closest point of a geometric primitive.

##### area
 Real area( Box ) Real area( Rectangle2D ) Real area( Circle2D ) Real area( Path ) Integer area( Region ) 

Calculates the surface area of a given geometric primitive.

For Path primitive the path needs to be closed and the surface area enclosed by the path is calculated. The path must not intersect with itself (improper result is returned in that case).

For Region primitive the result (of type Integer) is equivalent to the number of pixels active in the region.

##### dot
 Real dot( Vector2D, Vector2D ) Real dot( Vector3D, Vector3D ) 

Calculates the dot product of two vectors.

##### normalize
 Vector2D normalize( Vector2D ) Vector3D normalize( Vector3D ) 

Normalizes the specified vector. Returns a vector with the same direction but with length equal 1. When provided with zero length vector returns a zero length vector as a result.

##### createVector
 Vector2D createVector( Point2D point1, Point2D point2 ) Vector2D createVector( Real direction, Real length ) 

Creates a two dimensional vector (a Vector2D structure). First variant creates a vector between two points (from point1 to point2). Second variant creates a vector pointing towards a given angle (in degrees) and with specified length.

##### createSegment
Segment2D createSegment( Point2D start, Real direction, Real length )

Creates a two dimensional segment (a Segment2D structure) starting at a given start point, pointing towards a given direction (in degrees) and with specified length.

##### createLine
 Line2D createLine( Point2D point1, Point2D point2 ) Line3D createLine( Point3D point1, Point3D point2 ) Line2D createLine( Point2D point, Real direction ) 

Creates a line (a Line2D or Line3D structure). First two variants create a line that contains both of the specified points. Third variant creates a line containing specified point and oriented according to the specified angle (in degrees).

##### translate
 Point2D translate( Point2D point, Vector2D translation ) Point2D translate( Point2D point, Real direction, Real distance ) 

Moves a point.

First variant of the function moves a point by the specified translation vector. Second variant moves a point towards a specified direction (defined by angle in degrees) by an absolute distance.

##### toward
Point2D toward( Point2D point, Point2D target, Real distance)

Moves a point in the direction of the target point by an absolute distance. The actual distance between point and target does not affect the distance moved. Specifying a negative distance value results in moving the point away from the target.

##### scale
 Point2D scale( Point2D point, Real scale ) Point2D scale( Point2D point, Real scale, Point2D origin ) 

Moves a point by relatively scaling its distance from the center of the coordinate system (first function variant) or from the specified origin point (second function variant).

##### rotate (geometry)
Point2D rotate( Point2D point, Real angle, Point2D origin )

Moves a point by rotating it around the specified origin point (by an angle specified in degrees).

### Functions of type String

On text arguments it is possible to call functions (according to object function call operator) processing or inspecting a text string, e.g.:

outText = inText.Replace( "to-find", inNewText.ToLower() )


The type of String provides the following object functions:

##### Substring
 String arg.Substring( Integer position ) String arg.Substring( Integer position, Integer length ) 

This function returns the specified part of text. The first argument defines the position (starting from zero) on which the desired part starts in text. The second argument defines the desired length of returned part of text (this length can be automatically shortened when it exceeds the text length). Leaving out the second argument results in returning the part of text from the specified position to the end of text.

##### Trim
String arg.Trim()

Returns argument value, from which the whitespace characters have been removed from the beginning and the end.

##### ToLower
String arg.ToLower()

Returns argument value, in which all the upper case letters have been changed to their lower case equivalents.

##### ToUpper
String arg.ToUpper()

Returns argument value, in which all the lower case letters have been changed to their upper case equivalents.

##### Replace
String arg.Replace( String find, String insert )

Searches text for all occurrences of the value entered as the first argument and replaces such occurrences with the value entered as the second argument. Text search is case sensitive.

This function searches the source text consecutively from left to right and leaps the occurrences immediately after finding them. If the sought-after parts overlap in the text, only the complete occurrences found this way will be replaced.

##### StartsWith
Bool arg.StartsWith( String )

This function returns True only if text contains at its beginning (on the left side) the value entered as the argument (or if it is equal to it). Text search is case sensitive.

##### EndsWith
Bool arg.EndsWith( String )

This function returns True only if text contains at its end (from the right side) the value entered as the argument (or if it is equal to it). Text search is case sensitive.

##### Contains
Bool arg.Contains( String )

This function returns True only if text contains (as a part at any position) the value entered as the argument (or if it is equal to it). Text search is case sensitive.

##### Find
 Integer arg.Find( String ) Integer arg.Find( String, Integer ) 

This function searches in text for the first occurrence of the part entered as the argument (it performs searching from left to right) and returns the position, at which an occurrence has been found. It returns -1 when the sought-after substring doesn't occur in text. Text search is case sensitive.

Optionally, as the second function argument, one can enter the starting position from which the search should be performed.

##### FindLast
 Integer arg.FindLast( String ) Integer arg.FindLast( String, Integer ) 

This function searches in text for the last occurrence of the part entered as the argument (it performs search starting from right) and returns the position, at which an occurrence has been found. It returns -1 when the sought-after substring doesn't occur in text. Text search is case sensitive.

Optionally, as the second function argument, one can enter the starting position from which the search should be performed (and proceed in the direction of text beginning).

##### IsEmpty
Bool arg.IsEmpty()

This function returns True if text is empty (its length equals 0).

### Structure constructors

As part of formulas, you can pass and access fields of any structures. It's also possible to generate a new structure value, which is passed to further program operations.

In order to generate a structure value, a structure constructor (with syntax identical to the function with the name of the structure type) is used. As part of structure parameters, structure fields values should be entered consecutively. E.g. the constructor below generates a structure of type Box, starting in point 5, 7, with width equal to 100 and height equal to 200:

Box(5, 7, 100, 200)

It is also possible to create a structure object with default value by calling the constructor with empty parameters list:

Box()

Not all structure types are available through constructors in formulas. Only structures consisting of fields of primitive data types and not requiring specific dependencies between them are available. E.g. types such as Box, Circle2D or Segment2D consist of arithmetic types and due to this creating them in formulas is possible. Types such as Image, Region or Path have complex data blocks describing primitives and therefore it's not possible to create them in formulas.

Some structures have additional requirements on field values (e.g. Box requires that width and height be non-negative). When such a requirement is not met a Domain Error appears during program runtime.

### Typed Nil constructors

Nil symbol, representing an empty value of conditional types, does not provide the data type by itself. In constructions where providing a concrete data type of Nil value is necessary (like array construction or generic function call) it is possible to use a typed Nil construction by calling data type name and proving a single Nil symbol as the argument:

 Integer(Nil) Box(Nil) Segment2D(Nil) 

## Examples

#### Summing two integer values

 Filter inputs: inA of type Integer inB of type Integer Filter outputs: outSum of type Integer
 outSum = inA + inB 

#### Linear interpolation of two integer values

Having given two integer values and the position between them in form of a real number 0...1, the task is to compute the interpolated value in this position.

 Filter inputs: inA of type Integer inB of type Integer inPos of type Real Filter outputs: outValue of type Integer
 outValue = integer(round( inA * (1 - inPos) + inB * inPos )) 

A simple weighted averaging of two given values is performed here. Due to the multiplication by real values, the intermediate averaging result is also a real value. It's necessary then to round and convert the final result back to integer value.

#### Computing a center of Box primitive

Box is a data structure consisting of four fields of type Integer: X, Y, Width and Height. Having given an object of such primitive, the task is to compute its center in form of two integer coordinates X and Y.

 Filter inputs: inBox of type Box Filter outputs: outX of type Integer outY of type Integer
 outX = inBox.X + inBox.Width div 2 outY = inBox.Y + inBox.Height div 2 

#### Generating a structure

In the previous example, data used in a formula is read from a primitive of type Box. Such primitive can also be generated inside of a formula and passed to an output. In this example, we'd like to enlarge a Box primitive by a frame of given width.

 Filter inputs: inBox of type Box inFrame of type Integer Filter outputs: outBox of type Box
 outBox = Box( inBox.X - inFrame, inBox.Y - inFrame, inBox.Width + inFrame*2, inBox.Height + inFrame*2 ) 

#### Partial conditional execution

In case of working with conditional types, it's possible, as part of formula blocks, to use primitive types and to use conditional filters execution, including conditional execution of entire formula blocks. It's also possible to pass conditional execution inside formulas. This way, only a part of formulas of a block, or even only a part of a single formula, is executed conditionally.

In the simple summing shown below, parameter B is of a conditional type and this conditionality is passed to output.

 Filter inputs: inA of type Real inB of type Real? inC of type Integer Filter outputs: outValue of type Real?
 outValue = inA + inB + inC 

Formula content itself doesn't contain any specific elements related to a conditional parameter. Only formula output is marked with a conditional type. An occurrence of an empty value in input causes aborting execution of further operators and moving an empty value to output, in a similar way to operations on filters.

#### Replacing an empty value with a default object

If the conditional output type and thereby the conditional execution mode of following filters were not desired in the example above, it's possible to resolve the conditional type still in the same formula by creating a connection with a non-conditional default value.

 Filter inputs: inA of type Real inB of type Real? inC of type Integer Filter outputs: outValue of type Real
 outValue = (inA + inB + inC) ?? 0 

Addition operators still work on conditional types, the entirety of their calculations can be aborted when an empty value occurs. The result is however merged with a default value of 0. If summing doesn't return a non-empty result, then the result value is replaced with such non-empty value. In such case, an output doesn't have to be of conditional type.

#### Empty array response

In order to find the maximal value in an array of numbers, you can use the max function, it requires although a non-empty array. If an explicit reaction to such case is possible, we can define it by a condition and thereby avoid an error by passing an empty sequence to input.

 Filter inputs: inElements of type IntegerArray Filter outputs: outValue of type Integer
 outValue = (inElements.Count > 0) ? max(inElements) : 0 

In the example above a value of zero is entered instead of maximum of an empty array.

#### Range testing

Let's assume that we test a position of some parameter, which varies in the range of -5...10 and we'd like to normalize its value to the range of 0...1. What's more, the reaction to an error and to range overrun by a parameter is returning an empty value (which means conditional execution of further operations).

 Filter inputs: inParameter of type Real Filter outputs: outRangePos of type Real?
 outRangePos = (inValue >= -5 and inValue <= 10) ? (inValue + 5) / 15 : Nil 

#### Choosing a constant enumeration value

If block results should control operations which take enumeration types as parameters, then it's possible to generate values of such types as part of formulas. In the example below we'd like to determine the sorting direction, having given a flag of type Bool, which determines, if the direction should be opposite to the default one.

 Filter inputs: inReverse of type Bool Filter outputs: outOrder of type SortingOrder
 outOrder = inReverse ? SortingOrder.Descending : SortingOrder.Ascending 

#### Adding integer values of the loop

This example works in a loop, in each iteration there is some value passed to the inValue input and the goal is to sum these values. The prev operator returns 0 in the first iteration (as defined by its second argument). In each iteration the value of inValue input is added to the sum from the previous iteration.

 Filter inputs: inValue of type Integer Filter outputs: outSum of type Integer
 outSum = prev(outSum, 0) + inValue 
 Previous: Macrofilters Next: Error Handling