:- module(_,_).

% Example of Structure Inspection: Arrays

% An 'array' addition using functor/3 arg/2
% Explanations assume mode: add_arrays(+,+,?)
% i.e., we provide the first two arrays and obtain the sum.
% Step through in the debugger to see its operation!

add_arrays(A,B,C):-
    functor(A,array,N), % Gets length N from array A
    functor(B,array,N), % Checks that array B is of same length
    functor(C,array,N), % Creates an array C to hold the result
    add_elements(N,A,B,C).

add_elements(0,_A,_B,_C).
add_elements(I,A,B,C):-
    I>0, 
    arg(I,A,AI), 
    arg(I,B,BI), 
    arg(I,C,CI),
    CI is AI + BI, 
    I1 is I - 1,
    add_elements(I1,A,B,C).

% ?- add_arrays(array(1,2,3),array(4,5,6),R).
% ?- add_arrays(array(1,2,3),array(4,5,6),array(5,7,9)).
% ?- add_arrays(array(1,2,3),array(4,5),R).


% Alternative, using lists instead of structures: 

add_lists([],[],[]).
add_lists([X|Xs],[Y|Ys],[Z|Zs]):-
    Z is X + Y,
    add_lists(Xs,Ys,Zs).

% Try: 
% ?- add_lists([1,2,3],[4,5,6],R).
% ?- add_lists([1,2,3],[4,5,6],[5,7,9]).
% ?- add_lists([1,2,3],[4,5],R).
