Arrays in Prolog

Our first example demonstrates how to work with arrays in Prolog. In Prolog, lists are more commonly used for sequences of elements, but we can simulate arrays using compound terms.

% Define the main predicate
main :-
    % Create an "array" of 5 integers, initially all 0
    create_array(5, A),
    writeln('emp: '), write(A), nl,

    % Set a value at an index
    set_array(A, 4, 100, A1),
    writeln('set: '), write(A1), nl,

    % Get a value at an index
    get_array(A1, 4, Value),
    writeln('get: '), write(Value), nl,

    % Get the length of the array
    array_length(A1, Length),
    writeln('len: '), write(Length), nl,

    % Create and initialize an array in one line
    B = array(1,2,3,4,5),
    writeln('dcl: '), write(B), nl,

    % Create a 2D array
    create_2d_array(2, 3, TwoD),
    fill_2d_array(TwoD, FilledTwoD),
    writeln('2d: '), write(FilledTwoD), nl.

% Helper predicates
create_array(N, array(A)) :- length(A, N).

set_array(array(A), Index, Value, array(NewA)) :-
    nth0(Index, A, _, Rest),
    nth0(Index, NewA, Value, Rest).

get_array(array(A), Index, Value) :-
    nth0(Index, A, Value).

array_length(array(A), Length) :-
    length(A, Length).

create_2d_array(Rows, Cols, array(A)) :-
    length(A, Rows),
    maplist(create_array(Cols), A).

fill_2d_array(array(A), array(Filled)) :-
    length(A, Rows),
    length(A, Cols),
    findall(array(Row),
            (between(1, Rows, I),
             length(Row, Cols),
             maplist(plus(I), Row)),
            Filled).

To run this program, save it to a file (e.g., arrays.pl) and use a Prolog interpreter. For example, with SWI-Prolog:

$ swipl -s arrays.pl -g main -t halt
emp: array([0,0,0,0,0])
set: array([0,0,0,0,100])
get: 100
len: 5
dcl: array(1,2,3,4,5)
2d: array([array([1,2,3]),array([2,3,4])])

Note that in Prolog, we’re using compound terms with the functor array to represent arrays. The elements are stored in a list inside this compound term. This allows us to distinguish between regular lists and our array representation.

We’ve implemented helper predicates to create arrays, set and get values, and work with 2D arrays. The concept of multi-dimensional arrays is simulated using nested compound terms.

Prolog doesn’t have mutable state, so operations that would modify an array in imperative languages (like setting a value) actually create a new array term in Prolog.

This example demonstrates how to work with array-like structures in Prolog, even though lists are more idiomatic for the language. In practice, Prolog programmers would typically use lists or other data structures more suited to the language’s paradigm.