Using cuts in prolog to select facts from database

坚强是说给别人听的谎言 提交于 2019-12-24 03:59:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!