5.3 Array Notation
Since our language has no type declarations, there is really
no difference between a structure and an array. In fact,
a structure can always be used as an array, creating it with
and accessing elements with
However, this can look clumsy, especially in arithmetic expressions.
ECLiPSe therefore provides array syntax which enables the
programmer to write code like
Within expressions, array elements can be written as variable-indexlist
or structure-indexlist sequences, e.g.
[eclipse 1]: Prime = a(2,3,5,7,11), X is Prime + Prime.
X = 10
Prime = a(2, 3, 5, 7, 11)
Indices run from 1 up to the arity of the array-structure.
The number of array dimensions is not limited.
X + M[3,4] + s(4,5,6)
To create multi-dimensional arrays conveniently, the built-in
is provided (it can also be used backwards to access
the array dimensions):
creates all structures with the functor [ ], this has
no significance other than reminding the programmer that
these structures are intended to represent arrays.
[eclipse]: dim(M,[3,4]), dim(M,D).
M = ((_131, _132, _133, _134),
(_126, _127, _128, _129),
(_121, _122, _123, _124))
D = [3, 4]
Array notation is especially useful within loops.
Here is the code for a matrix multiplication routine:
matmult(M1, M2, M3) :-
Sum1 is Sum0 + M1[I,K] * M2[K,J]
subscript(M3, [I,J], Sum)
5.3.1 Implementation Note
Array syntax is implemented by parsing variable-list and
structure-list sequences as terms with the functor subscript/2.
If such a term is then used within an arithmetic expression,
a result argument is added and the built-in predicate
is called, which is a generalised form of
and extracts the indicated array element.
X ---> subscript(X, )
M[3,4] ---> subscript(M, [3,4])
s(4,5,6) ---> subscript(s(4,5,6), )
When printed, subscript/2 terms are again printed in array notation,
unless the print-option to suppress operator notation ("O") is used.