Hi everybody, I'm having a little problem with finding sum of nested list in Prolog. So far what I have is

totalSum([],0).
totalSum([H|T],S):-
      totalSum(T,Sum),
      S is Sum + H.
totalSum([H|T],S):-
     totalSum(H,Sum1),
     totalSum(T,Sum2),
     S is Sum1+Sum2.

With first two predicates, I have no problems getting sum of not-nested list. Anybody with a tip as to how I can modify the third predicate so that it can handle nested list? I've tried passing off [H] instead of just H and many other but it hasn't worked so far. Any comment would be deeply appreciated.

Recommended Answers

All 6 Replies

Your second predicate is going to match and override whatever you do in your third predicate. You need to handle nested lists before you handle non-nested lists.

Thanks for the quick reply. While I agree with you but I have tried with third predicate before second and have encountered the same problem. I think the major problem lies with my logic in third predicate.

Well you have more problems than just that.

So you mean I have logic problems and more...? Could you point me to a general direction, like where my logic is wrong (I know my logic is flawed but I'm not sure exactly what).

All you need to do to fix your problem is look at your code and imagine what a prolog interpreter would do when interpreting it.

Rashakil was correct that the rule matching a single number needs to come last.

Here is a complete answer. Your first line also had to be changed:

totalSum([],N) :- N is 0.
totalSum([H|T],S):-
    totalSum(H,Sum1),
    totalSum(T,Sum2),
    S is Sum1+Sum2.
totalSum(N,S):-
    S is N.

and here are some examples of using it:

?- totalSum([1, 2, 3], N).
N = 6 .

?- totalSum([1, [2], 3], N).
N = 6 .

?- totalSum([1, [2, 3]], N).
N = 6 .

?- totalSum([1, [2, [3]]], N).
N = 6 .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.