Home > Back-end >  Prolog prefix sum of a list
Prolog prefix sum of a list

Time:02-04

I want to implement the prolog predicate prefixSum(L, R) that calculates the prefix sum of a list i.e:

?- prefixSum([1,2,3,4],R). R=[1,3,6,10].

Here is my solution so far:

prefixSum([],[]).
prefixSum([X], [X])
prefixSum([X|Xs], [R, Rs|T]):- 
    Rs is X   R,  prefixSum(Xs, T). 

any suggestions? Please help me out.

CodePudding user response:

prefix_sum(L, Ps) :-
    prefix_sum_(L, 0, Ps).
    
prefix_sum_([], _, []).
prefix_sum_([H|T], S, [P|Ps]) :-
    P is H   S,
    prefix_sum_(T, P, Ps).

Result in swi-prolog:

?- prefix_sum([1,2,3,4], Ps).
Ps = [1, 3, 6, 10].
  • Related