Prolog bagof, setof, findall predicates

2k Views Asked by At

How do I query database facts with 3 or more attributes in Prolog using bagof, setof. An example I have a defined a database students(name, grade,sport,gender). I want find a list of students that play a particular sport, say cricket. My current query

sport_list(L):- 
        bagof(S,N^G^D^students(N,G,S,D),L),
           S = cricket.

student(patash,5,rugby,male).
student(naomi,3,netball,female).
student(lepo,6,_,male).
student(diamal,4,cricket,male).
student(bonga,5,chess,female).
student(imi,6,cricket,male).
student(ayanda,3,_,female).
1

There are 1 best solutions below

0
tas On BEST ANSWER

You could model your knowledge base such that the third argument is none for unathletic students instead of _:

student(lepo,6,none,male).
student(ayanda,3,none,female).

Then you can define a predicate that describes atheletic students as being those who do not have none as sport:

athletic(S) :-
   dif(X,none),
   student(S,_,X,_).

Subsequently use athletic/1 in the single goal of sport_list/1:

sport_list(L):- 
   bagof(S,athletic(S),L).

That yields the desired result:

   ?- sport_list(L).
L = [patash,naomi,diamal,bonga,imi]