Reputation: 1322
I am fairly new to Prolog and I am trying to get my head around the concept of lists. An example that I am trying is:
value(a, 1).
value(b, 2).
value(a, 3).
value(a, 4).
value(c, 3).
I am trying to create a predicate which when queried find(a, List)
results in: List = [1, 3, 4].
It simply goes over all the facts and adds the matching ones to the list.
I've tried something like this. but it doesn't seem right at all:
find(X, List):-
value(X, D), append([D], [], [List|Rest]), find(X, [Head|List]).
Sorry about such a basic question. Any guidance is appreciated.
Note: I intend to extend the program by making it add all the values in the list.
Upvotes: 1
Views: 1076
Reputation: 426
Take a look here: http://www.swi-prolog.org/pldoc/doc_for?object=findall/3
I believe what your trying to do already exists, try this:
?- findall(X,value(a,X),List).
I don't have prolog installed on this machine so I can't perfectly test it, but that should get you what you're looking for.
Edit: Sorry managed to get into swi and realized i had 2 arguments reversed, see updated code now. Also tested it and it works :-)
Edit 2: As per the comment above, you could gather the values which match 'a' and get the sum you could combine into this:
?- findall(X, value(a,X), List), sumlist(List, Sum).
-Ken
Upvotes: 3