:- module(_,[sum/2],[assertions,regtypes,nativeprops]).

% Example program that sums the elements in an array

:- entry sum/2.

sum(array(A,ALen),R) :-
        array_len(array(A,ALen),ALen),
        ALen >= 0,
        sum_(0, array(A, ALen), 0, R).

sum_(I, array(A,Len), R0, R) :-
        array_len(array(A,Len),ALen),
        I >= ALen,
        R = R0.
sum_(I, array( A,ALen), R0, R) :-
        I < ALen,
        read(array(A, ALen), I, V),
        R1 is R0 + V,
        I1 is I + 1,
        sum_(I1, array(A, ALen), R1, R).

array_len(array(_A,ALen), ALen). % :- functor(A, _, Len).

read(array(A, Len), I, V) :-
        read_(A, Len, I, V).

:- pred read_(A,Len,I,V) : (constraint([I >= 0, I < Len])).
read_(A, Len, I, V) :-
        myread(A, Len, I, V).

% ---------------------------------------------------------------------------

:- use_module(library(lists),[nth/3]).

myread(A,_,I,V) :- I1 is I + 1, nth(I1,A,V). % assuming array is a list
