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).
setof/3
andbagof/3
indicate that the first argument is the term you wish to collect. So in this case, that would be the student name variable. Second argument should be the condition, and the 3rd argument is the list to collect into. So:setof(N, G^D^students(N, G, cricket, D), L).
Yourbagof
call collects sports intoL
, then attempts to unifyS
withcricket
. No collection of names occurs. – lurkerstudent/4
queries, you could usefindall(N, students(N, _, cricket, _), L).
– lurkerbagof
to exclude the case whereS
is a variable. Seevar/1
documentation.Try some things. Don't make us do all of your work for you. :) Easier, use an atom instead of an anonymous variable (_
) to mean "no sport". Why not usenone
or'no sport'
? That would solve the problem without additional logic. The anonymous variable is going to match anything. – lurker