简体   繁体   中英

How to only sum up values of a list in Prolog?

I've been given this code below:

returnValues(Value):-
collection(X,Y,Z),
total([X,Y|Z],Value).

This does work, but it sums up X,Y and Z. I'm looking for it to sum up Z only . Z is a list and I want to sum up the Values of Z.
Total is:

total([],0).   

total([Item|List],Sum):-
salary(Item,A), 
total(List,Rest),   
Sum is B + Rest.

I've tweaked the code a few times so that it only gives me values of X and Z, and only values of Y and Z, but I haven't been able to get values of Z only.

Sample input:

questionChildrenIncome(Name,Surname,CombinedIncome):-
family(Husband,person(Name,Surname,_,_),Children), 
total(Children,CombinedIncome),
CombinedIncome<100000,
member(Child,Children),
salary(Child,Salary),
Salary<30000.

You could just ignore X,Y like:

returnValues(Value):-
   collection(_,_,Z),
   total(Z,Value).

For your second comment you could write:

exclude([],[]).
exclude([H|T],[H|T1]):-salary(H,Salary),Salary<30000,exclude(T,T1).
exclude([H|T],T1):- salary(H,Salary),Salary>=30000,exclude(T,T1).

and change to :

questionChildrenIncome(Name,Surname,CombinedIncome):-
family(Husband,person(Name,Surname,_,_),Children), 
total(Children,CombinedIncome),
CombinedIncome<100000,
exclude(Children,Children)

. You could also write more simply exclude predicate like:

exclude([]).
 exclude([H|T]):-salary(H,Salary),Salary<30000,exclude(T).

which succeeds only if all children have salary<30000.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM