使用prolog中的cuts从数据库中选择事实 [英] Using cuts in prolog to select facts from database

查看:77
本文介绍了使用prolog中的cuts从数据库中选择事实的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该使用Prolog剪切从事实数据库中获取第一个,第二个和最后一个事实,我找到了一种获取第一个和第二个事实的方法,但是我找不到找到最后一个的解决方案事实是一个例子:

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).

仅选择第一个事实:first(X):-P(X),!.

仅选择第二个事实:second(Y):-P(X),P(Y),X\=Y,P(Y),!.

仅选择最后一个事实:?

Selecting the last fact only : ?

推荐答案

如果不使用否定,累加器和服务谓词成员,我看不到一种方法,但是由于否定(由于失败)是通过削减实现的,因此是我的赌注:

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).

代替\+ member(Elem,List)(读取Elem不在List中),您可以实现not_contains/2,并在其中进行显式剪切.

Instead of \+ member(Elem,List) (read Elem is not in List), you could implement a not_contains/2, with explicit cut inside.

顺便说一句,您的second/1谓词包含一个冗余调用:应该为

BTW your second/1 predicate contains a redundant call: should be

second(Y):-p(X),p(Y),X\=Y,!.

这篇关于使用prolog中的cuts从数据库中选择事实的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆