next up previous index
Next: The String Data Type Up: ECLiPSe-specific Language Features Previous: Loop/Iterator Constructs   Index

Subsections


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 functor/3 and accessing elements with arg/3. However, this can look clumsy, especially in arithmetic expressions.

ECLiPSe therefore provides array syntax which enables the programmer to write code like

[eclipse 1]: Prime = a(2,3,5,7,11), X is Prime[2] + Prime[4].
X = 10
Prime = a(2, 3, 5, 7, 11)
yes.
Within expressions, array elements can be written as variable-indexlist or structure-indexlist sequences, e.g.
X[3] + M[3,4] + s(4,5,6)[3]
Indices run from 1 up to the arity of the array-structure. The number of array dimensions is not limited.

To create multi-dimensional arrays conveniently, the built-in dim/2 is provided (it can also be used backwards to access the array dimensions):

[eclipse]: dim(M,[3,4]), dim(M,D).
M = []([](_131, _132, _133, _134),
       [](_126, _127, _128, _129),
       [](_121, _122, _123, _124))
D = [3, 4]
yes.
Although dim/2 creates all structures with the functor [], this has no significance other than reminding the programmer that these structures are intended to represent arrays.

Array notation is especially useful within loops. Here is the code for a matrix multiplication routine:

matmult(M1, M2, M3) :-
        dim(M1, [MaxIJ,MaxK]),
        dim(M2, [MaxK,MaxIJ]),
        dim(M3, [MaxIJ,MaxIJ]),
        (
            for(I,1,MaxIJ),
            param(M1,M2,M3,MaxIJ,MaxK)
        do
            (
                for(J,1,MaxIJ),
                param(M1,M2,M3,I,MaxK)
            do
                (
                    for(K,1,MaxK),
                    fromto(0,Sum0,Sum1,Sum),
                    param(M1,M2,I,J)
                do
                    Sum1 is Sum0 + M1[I,K] * M2[K,J]
                ),
                subscript(M3, [I,J], Sum)
            )
        ).

Implementation Note

Array syntax is implemented by parsing variable-list and structure-list sequences as terms with the functor subscript/2. For example:

X[3]          --->      subscript(X, [3])
M[3,4]        --->      subscript(M, [3,4])
s(4,5,6)[3]   --->      subscript(s(4,5,6), [3])
If such a term is then used within an arithmetic expression, a result argument is added and the built-in predicate subscript/3 is called, which is a generalised form of arg/3 and extracts the indicated array element.

When printed, subscript/2 terms are again printed in array notation, unless the print-option to suppress operator notation ("O") is used.


next up previous index
Next: The String Data Type Up: ECLiPSe-specific Language Features Previous: Loop/Iterator Constructs   Index
Warwick Harvey
2004-08-07