问题
score(Movies,Total) :-
findall(Money,(member(Movie,Movies),takings(Movie,Money)),Profit),
sum_list(Profit,Total)
I want to convert this rule using recursion but I am not sure how. Help! Link to the previous question that answers this one : Sum up data from facts
回答1:
% base case
score([],0).
% recursive case
score([Movie|Movies],Total) :-
takings(Movie,Profit),
score(Movies,Total0),
Total is Total0 + Profit.
Example run
?- score([robots,hulk,bad_boys_ii],Y).
Y = 749200000.
Explanation of code
List in Prolog are recursively constructed and deconstructed using the | operator. As 0 is the initial value for counting integers, [ ], known as the empty list, is the initial value for a closed list. To recursively build to the front of a closed list one uses the current list and the | operator. When using | in Prolog it is common to refer to the item being added as the Head, (H) and the current closed list being added to as the Tail, (T), and this why you often see the notation [H|T] when talking about list in Prolog.
So to construct the list [1,2,3] would be [] then add 1, [1].
?- L = [1|[]].
L = [1].
To add 2 would be [1] then add 2, [2,1].
?- L = [2|[1]].
L = [2, 1].
To deconstruct the list [1,2,3] would use variables so [H|T] will become H being 1 with T being [2,3].
?- [H|T] = [1,2,3].
H = 1,
T = [2, 3].
When you get to the end of the list it is just [] with out a head.
?- [H|T] = [1].
H = 1,
T = [].
So in the code [Movie|Movies]
takes input list of movies and unifies the head of the list Movie
with the first movie and passes the tail of the list Movies
recursively to the predicate. Only when the list is empty will the clause score([],0)
match and unify the 0 with Total0
in score(Movies,Total0)
.
I know this can have a lot more detail in explanations, but these explanations are all over the place in Prolog examples.
回答2:
This way :)
recursive_score([H], CurrentMoney):-
takings(H, Value),
CurrentMoney is Value.
recursive_score([H|T], Money):-
takings(H, Value),
recursive_score(T, CurrentMoney),
Money is CurrentMoney + Value.
来源:https://stackoverflow.com/questions/60582468/prolog-findall-3-rule-convert-to-recursive-rule