Define and use arrays

In Strawberry Prolog you can define and use arrays as easy as in procedure languages. To define an array use the built-in predicate array. This predicate has three arguments:

array( Name, StartSize, Init )

The name can be any Prolog atom which will be used as a name of your array. Of course, you cannot use this atom as a name for other array or object. The StartSize argument has to be integer showing the size of this array at its creation. The type of the array elements will be the type of Init argument. All elements of this array will be initialized with the value of Init argument.

After defining your array you can easily use it by including in the expressions members of the type of my_array( N ) , where my_array is the atom which you choose for name of your array and N is integer expression which gives the number of the element you need. The value of N must be bigger or equal to zero and less than the size of the array, i.e. the first element of the array has index 0.

If you want to change the value of any element of the array then simply write:

my_array( N ) := V

where N is the number of the element which value you want to change and V is the new value which you want to give to this element. The creation of array and change of its elements will be stable on backtracking.

?-
array(my_array, 10, 0),
my_array(5):=13,
write(my_array(2+3)).