Define a recursive rule, in the form of sum(Lst, Total), which can calculate the sum of a list of stated, where Lst is in the format of [[s1, p1], [s2, p2], … [sn, pn]]

so i only want sum p and s is not numbers. how can i done this?

sum([[az, ​7​], [ca, ​40​], [ne, ​3​], [ut, ​3​], [or, ​4​],Total).

it should return Total = 60. but my code is not returning anything

i have

sum([[_,X]|T],Total) :- 
    sum(T,Rest),
    Total is X + Rest. 

2 Answers

2
Community On

sum(L,Total):- total(L,0,Total).

sum([],Total,Total).

sum([[_|HT]T],Temp,Total) :- Temp1 is temp+HT,total(T,Temp1,Total).

2
Éric López Clavero On

You're only missing the base case where the list is empty!

sum([],0).

sum([[_,X]|T],Total) :- 
    sum(T,Rest),
    Total is X + Rest.