1
votes

I need a predicate which plus of a list of lists in prolog using pure logic and natural number notation. For example for the predicate :

?-totalPlus([ [s(0)],[s(0),s(0)],[s(s(0))] ], Res).

The result must be:

Res= s(s(s(s(s(0))))).

This is my implementation but it only returns the plus of the first list:

    plusNat(0,X,X).
    plusNat(s(X),Y,s(Z)):-plusNat(X,Y,Z).

    plusList([],0).
    plusList([X|Xs], S) :- plusList(Xs,SXs), plusNat(X,SXs,S).

    totalPlus([],_).
    totalPlus([X|Xs],Y):-totalPlus(Xs,_), plusList(X,Y).
    ------------------

    ?-totalPlus([ [s(0)],[s(0),s(0)],[s(s(0))] ], Res).
      Res= s(0).

Thanks in advance!

2
Apply the concept you used in plusList a second time.Willem Van Onsem
using another predicate plusList2 called in plusList for example?guilieen
yes, that is correct.Willem Van Onsem
i already prove and it doesn't work =( can you put an example?guilieen

2 Answers

1
votes

I Finally added a plus predicate to accumulate the result , it is a possible solution and it works :

plusNat(0,X,X).
plusNat(s(X),Y,s(Z)):-plusNat(X,Y,Z).
plusList([],0).
plusList([X|Xs],S) :- plusList(Xs,SXs), plusNat(X,SXs,S).
totalPlus([],0).
totalPlus([X|Xs],Y):-totalPlus(Xs,Z), plusList(X,K), plusNat(K,Z,Y).
0
votes

It might be better to implement the plusList/2 with a helper predicate plusList/3 that uses an accumulator, like:

plusList(L, S) :-
    plusList(L, 0, S).

plusList([], S, S).
plusList([H|T], Si, So) :-
    plusNat(H, Si, S),
    plusList(T, S, So).

The nice thing is that we can make use of this helper predicate to avoid double work when we add the sums of the sublists together for totalPlus:

totalPlus(LL, S) :-
    totalPlus(LL, 0, S).

totalPlus([], S, S).
totalPlus([H|T], Si, So) :-
    plusList(H, Si, S),
    totalPlus(T, S, So).