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.

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.

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.

This question has already been answered. Start a new discussion instead.