Sum up data from facts

空扰寡人 提交于 2020-04-18 12:31:17

问题


(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

  1. You can put more than a simple query in the Goal for findall/3, e.g.
(member(Movie,Movies),takings(Movie,Money))
  1. [Movies] is used wrong as needed. It should be just Movies

Example run

?- score([robots,hulk,bad_boys_ii],Y).
Y = 749200000.


来源:https://stackoverflow.com/questions/60580787/sum-up-data-from-facts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!