问题
(Given a list of movies, write a PROLOG rule to add and display the total takings.) This is my question I am basically trying to add an integer value give a list of movies from the list below. I am quite new in Prolog and I don't really understand how things work.
takings(air_force_one,315000000).
takings(american_beauty,336000000).
takings(american_pie,201700000).
takings(american_wedding,230700000).
takings(armageddon,554600000).
takings(as_good_as_it_gets,313300000).
takings(austin_powers_in_goldmember,289000000).
takings(babe,249000000).
takings(back_to_the_future,350600000).
takings(back_to_the_future_part_ii,332000000).
takings(back_to_the_future_part_iii,243700000).
takings(robots,245600000).
takings(hulk,241700000).
takings(bad_boys_ii,261900000).
The Rule I have written so far works for only one movie. Example:
?- score([robots],Y).
Y = 245600000.
?- score([robots,hulk],Y).
false.
?- score([robots,hulk,bad_boys__ii],Y).
false.
Rule written :
score([Movies], Money):-
findall(Profit,(takings(Movies, Profit)), ListOfProfit),
sum_list(ListOfProfit, Money).
Related question asking for a recursive answer.
回答1:
What you seek is
score(Movies,Total) :-
findall(Money,(member(Movie,Movies),takings(Movie,Money)),Profit),
sum_list(Profit,Total).
The parts you needed are
- You can put more than a simple query in the Goal for findall/3, e.g.
(member(Movie,Movies),takings(Movie,Money))
[Movies]
is used wrong as needed. It should be justMovies
Example run
?- score([robots,hulk,bad_boys_ii],Y).
Y = 749200000.
来源:https://stackoverflow.com/questions/60580787/sum-up-data-from-facts