Arrays

The purpose of arrays is to group arguments. For example, the function alldiff does not take a list of integer expressions, it takes an array of them.

Arrays are created using the following syntax:

Arrays may (but are not obliged to) define their type (such as intArray or intExprArray). If the type is not specified, then it is assumed to be the most specific type considering the items of the array. Note that empty arrays must have their type specified: therefore intArray[] is accepted, but [] returns an error.

Arrays consist of a list of items delimited by commas. The whole list is enclosed in square brackets. Operator double-dot .. can be used as a shortcut to define consecutive integer values. For example, intArray[1, 3..6, 10] is equivalent to intArray[1, 3, 4, 5, 6, 10].

To simplify automatic generation of models in the CPO file format, a trailing comma is allowed in arrays. For example intArray[1, 5, 9,] is equivalent to intArray[1, 5, 9]. Note that intArray[,] is an error.

There is no way to subscript an array:


let arr = [1, 2, 3, 4, 5];
let foo = arr[2]; // <--- This is an error

There is an element function that does something similar, however the difference is that the index is an expression and the result value is also an expression, not a constant.

Arrays are always indexed from zero (first item has index 0, second index 1 etc). This fact is important for example in constraint inverse.

Example

Function count returns the number of times a given value (the second argument) occurs within an array of expressions (the first argument - an array). In the following example, exactly two of the variables x1, x2, x3, x4 and x5 must take value 3:


x1 = intVar(1..20);
x2 = intVar(1..20);
x3 = intVar(1..20);
x4 = intVar(1..20);
x5 = intVar(1..20);
count([x1, x2, x3, x4, x5], 3) == 2;

Array types

The main types of arrays are:

intArray
Array of integer constants (type int).
floatArray
Array of floating-point constants (type float).
intExprArray
Array of integer expressions (type intExpr).
floatExprArray
Array of floating-point expressions (type floatExpr).
intervalVarArray
Array of interval variables (type intervalVar).
cumulExprArray
Array of cumulative expressions (type cumulExpr).
sequenceVarArray
Array of sequence variables (type sequenceVar).

Hierarchy of array types

Of course, intArray or intExprArray can be used anywhere where floatExprArray is required. The following diagram shows the hierarchy of basic array types: