Home > Net >  Prolog Predicate that returns Sum of weights of items in a list
Prolog Predicate that returns Sum of weights of items in a list

Time:11-25

I want to write a prolog predicate that takes in a list of items, searches for the weights of these items, and returns their sum. I got the corresponding weights but I don't know how to get the sum in the predicate it's not working.

This is my very first project in Prolog so I'm still learning. Thank you :)

weight(mum,60).
weight(dad,85).
weight(alfie,20).
weight(bianca,25).
weight(daisy,50).
weight(puppy,10).
list_sum([],0).
list_sum([Head|Tail], TotalSum):-
    list_sum(Tail, Sum1),
    TotalSum is Head Sum1.

total_weight([], []).
total_weight([H_entity | T_entity], [H_weight | T_weight]) :-
    weight(H_entity, H_weight),
    total_weight(T_entity, T_weight).

This returns a list of the weights of the items given. I tried getting the sum but it didn't work.
The output I am looking for is total_weight([mum,dad,puppy],W): W=155

CodePudding user response:

Try this:

?- total_weight([mum,dad,puppy], WeightList), sum_list(WeightList, Sum).
WeightList = [60, 85, 10],
Sum = 155.

EDIT

Combining both predicates:

sum_of_weights([], 0).
sum_of_weights([E|Es], S) :-
    sum_of_weights(Es, T),
    weight(E, W),
    S is T   W.

Example:

?- sum_of_weights([mum,dad,puppy], S).
S = 155.
  • Related