Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with prolog Lists

Status
Not open for further replies.

BeginnerPro

Programmer
Dec 27, 2010
1
GB
Hi,

Im new to Prolog and was looking for some assistance. What i am trying to do is basically get the sum of the list of list, if that makes sense? lol

What i am trying to achieve is.... sum([ [1,2],[3,4],[5,6] ]). should return:
Number Of Lists: 3
List 1
3
List 2
7
List 3
11
....etc

I can get the Number of Lists which is fairly simple but im not quite sure how to loop through the List and then for each List add the numbers up. Am i making this more complicated than it actually is? lol!

If anyone can help me or point me in the general direction that would be great.

Thanks in advance
 
To calculate the sum of the list, you must walk through the list, adding each element you meet in an accumulator. When the list is finished, you unified the accumulator with the result
basically you must have two clauses for the predicate sum_of list :
Code:
% What to do when the list is not empty
sum_of_list([H | T], Acc, Sum) :-
 ......

% What to do when the list is empty
sum_of_list([], ..., ...).
 
Calculate the sum of a list of lists

%calculates the sum of one list of lists
sum_List([],[]).
sum_List([[E|T]|Rest],[Current|RestResult]):- soma(T,R),Current is E + R,sum_List(Rest,RestResult).

%calculates the sum of one list of numbers
soma([],0):-!.
soma([E|T],S):-soma(T,R),S is E+R.


?-sum_List([[9,10],[1,2,4,4],[2,3,4,5]],L).
?-L = [19, 11, 14].
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top