简体   繁体   中英

Appending element to a list in prolog

I have a database of 5 members with an Income attribute. I want to sum the incomes of all the members. For this, I want to create a list of incomes and add them.

To create a list of incomes, I have written the append predicate as

append(Element, List, OutputList)

this adds element to the list and returns it in outputlist.

Now I want to take the income of every member and put it in a list and add the elements of the list. But I am unable to put all the elements in the list. Can you please help me in creating these 2 predicates. This is the code that I have written.

member(a,2).
member(b,1).
member(c,2).
member(d,3).
member(e,1).

append([],L,L).
append(Elem,L,X):- append([],[Elem|L],X).

% this add predicate is incorrect
add(L,X) :- member(_,Income),append(Income,L,L),X is L.

I want to generate the output list as [2,1,2,3,1] and sum them and get 2+1+2+3+1 = 9.

You need to collect ALL of the results for the query member(_, Income) , and then to sum them up. To collect all of the matching results you can use one of the metapredicate bagof , setof or findall . Your task can be accomplished by simply:

member(a,2).
member(b,1).
member(c,2).
member(d,3).
member(e,1).


sum([], 0).
sum([H|T], S) :-
    sum(T, S1),
    S is S1 + H.

and then the query:

findall(Income, m(_, Income), Incomes), sum(Incomes, S).

gives you:

Incomes = [2, 1, 2, 3, 1],
S = 9

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