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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding numbers in a List?

Status
Not open for further replies.

Netherbeast

Programmer
Jun 4, 2002
89
US
Im new to this language and am having a hard time manipulating atoms in the list.

All im trying to do is add the numbers of a given list, say like add([2, 3, 4], Total).
and the Total = 9.

I can count how many elements are in the list using this code:
len([], 0).
len([CAR|CDR], X) :- len(CDR, X1), X is X1+1.

but getting it to add all the numbers is harder than I thought.

Thanks in advance
 
Try using an accumulator to keep track of the sum so far.

add(Lst,Sum) :- add(Lst,Sum,0).

add([],Sum,Sum).
add([X|Xs],Sum,Acc) :- NewAcc is Sum+Acc,
add(Xs,Sum,NewAcc).

I haven't tested it, but this should do the trick. The add/2 rule sets the accumulating helper to start at 0. Then the helper moves through the list and adds each value to some holder called Acc. When the list is empty, it copies the value currently in Acc into Sum.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top