问题
I'm supposed to use Prolog cuts to get the first , the second and the last fact from the facts database , I found a way to get the first and the second but I can't find a solution for retrieving the last fact here is an example :
P(jack).
P(john).
P(alice).
P(sarah).
P(kyle).
Selecting the first fact only : first(X):-P(X),!.
Selecting the second fact only : second(Y):-P(X),P(Y),X\=Y,P(Y),!.
Selecting the last fact only : ?
回答1:
I can't see a way without using negation, an accumulator, and the service predicate member, but since negation (by failure) is implemented with cuts, here is my bet:
last_(Y) :- collect([], [Y|_]).
collect(Seen, L) :-
p(X), \+ member(X, Seen), collect([X|Seen], L).
collect(All, All).
Instead of \+ member(Elem,List) (read Elem is not in List), you could implement a not_contains/2, with explicit cut inside.
BTW your second/1 predicate contains a redundant call: should be
second(Y):-p(X),p(Y),X\=Y,!.
来源:https://stackoverflow.com/questions/21041164/using-cuts-in-prolog-to-select-facts-from-database