0

I am trying to perform a sumList function in prolog that takes the input: sumList([1,[2,3],[4],5],X). and returns X=15.

I understand how to sum a simple list and a list of lists(ie [1,2,3,4,5] & [[1,2,3],[4,5]]) but i am getting errors because i am not properly handing the multiple inner lists(because i do not yet know how to, i havent encountered this before), i was told i have to use atom or atomic by a college somehow but i haven't seen a clear example on how this is done. any sml code i could translate or prolog code that could help me sum the list [1,[2,3],[4],5] would be greatly appericated. thanks!

false
  • 10,264
  • 13
  • 101
  • 209
Laura
  • 3
  • 1

2 Answers2

0

In SWI Prolog (just not sure about ANSI) the atomic(X) predicate can tell you whether the X is list or a number (in your case). It can be used write the sum predicate by recursively calling itself when a list is encountered, or just add the element to a sum if a simple number:

sum([], 0).
sum([H|T], S) :-
    atomic(H),
    sum(T, S1),
    S is H + S1.
sum([H|T], S) :- 
    sum(H, S1),
    sum(T, S2),
    S is S1 + S2.
Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
  • thanks so much! that is amazing i have been struggling trying to find any decent examples of atom or atomic(more then their general definitions) for half the afternoon. Yes i am working in SMI prolog. – Laura Dec 04 '14 at 22:38
  • i do not have the reputation to upvote @Eugene but i did accept the answer, i really appreciate the help in understanding atomic and the example. – Laura Dec 08 '14 at 18:33
0

Prolog treats an [] as atomic. The implementation from Eugene Sh. doesn't handle the case when H is an empty list []. Checking if H is an empty list in the second clause solves the issue.

sum([], 0).
sum([H|T], S) :-
    atomic(H),
    H\==[], % fail incase H is an empty list 
    sum(T, S1),
    S is H + S1.
sum([H|T], S) :- 
    sum(H, S1),
    sum(T, S2),
    S is S1 + S2.