0
votes

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!

2

2 Answers

0
votes

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.
0
votes

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.