0

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.

2
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by Rashakil Fol
0

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.

0

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.

0

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).

0

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.