问题
How would I be able to obtain the totalcost and loop through each employee to get the cost individually?
Expected output:
?- make_team([batman, superman, aquaman], Heroes, TotalCost).
Heroes = [[batman, bruce, wayne, 342000], [superman, clark, kent, 475000], [aquaman, arthur, curry, 5000]],
TotalCost = 822000.
% Returns a list of available heroes.
% Each hero's information is also stored as a list.
employees(E) :- E = [
[superman, clark, kent, 475000],
[batman, bruce, wayne, 342000],
[wonder_woman, diana, prince, 297000],
[green_arrow, oliver, queen, 210000],
[flash, barry, allen, 184000],
[aquaman, arthur, curry, 5000] ].
% Helper rule that may be used to extract information from an
% employee. For instance, if you know an employee's name,
% you can use this rule to look up their salary.
hero(HeroName, SecretIdentFname, SecretIdentLname, Salary) :-
employees(EmpList),
member(H, EmpList),
H = [HeroName, SecretIdentFname, SecretIdentLname, Salary].
% Given a list of hero names, return the list of heroes
% and the total cost of all heroes. (Since there should
% only be one match, you might consider using a green cut).
make_team([], [], 0).
make_team([HeroName|Tail], HeroList, TotalCost) :-
employees(EmpList),
% CODE HERE
回答1:
employees(E) :- E = [
[superman, clark, kent, 475000],
[batman, bruce, wayne, 342000],
[wonder_woman, diana, prince, 297000],
[green_arrow, oliver, queen, 210000],
[flash, barry, allen, 184000],
[aquaman, arthur, curry, 5000] ].
make_team([], [], 0).
make_team([HeroName|Tail], HeroList, TotalCost) :-
employees(EmpList),
make_team(Tail, Z1, Z2),
member( [HeroN, A, B, C], EmpList),
HeroN == HeroName,
append([[HeroN,A,B,C]],Z1,HeroList),!,
TotalCost is Z2 + C.
Try that.
来源:https://stackoverflow.com/questions/61828694/how-to-obtain-the-cost-of-each-employee-in-prolog