I would like to create a list of all the exam(A,B) contained in the knowledge base:
exam([a, 26]).
exam([b, 30]).
exam([c, 20]).
exam([d, 19]).
I know that i can simply use:
exams(L) :- findall(X, exam(X), L).
But since i want to write my own roles, i wrote the following:
exams([exam([A,B])]) :- exam([A,B]).
exams([exam([A,B])|Ex]) :- \+(member(exam([A,B]),Ex)), exams(Ex).
Why with a query like ?- exams(X). the system answers as follow:
?- exams(X).
X = [exam([a, 26])] ;
X = [exam([b, 30])] ;
X = [exam([c, 20])] ;
X = [exam([d, 19])] ;
false.
And doesn't give me any list with more than just one exam, also if the following query returns true:
?- exams([exam([a,26]),exam([b,30])]).
true .
a possibility is
exams(L) :- exams([], R), !, reverse(R, L).
exams(S, L) :- exam(E), \+ memberchk(exam(E), S), exams([exam(E)|S], L).
exams(L, L).
but, apart learning about Prolog control flow, I cannot see any value in such solution. Maybe you should elaborate the reason that force you to avoid findall/3...
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.