Prolog,列表中Y之前的X [英] Prolog, X before Y in a List

查看:74
本文介绍了Prolog,列表中Y之前的X的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解序言时遇到麻烦,我必须在列表中查找X是否在Y之前.

I am having trouble understanding prolog, I have to find if X is before Y in a list.

所以我有一个带有空列表的基本情况

so I have a base case with an empty list

before(X, Y, [ ]).

现在我知道我想检查List中X的索引和Y的索引,如果indexX < indexY我想成功.

Now I know that I want to check the index of X and the index of Y in List and if indexX < indexY I want to have a success.

有人可以解释一个简单的方法吗?

Could someone explain a simple way to do this?

推荐答案

使用DCG,它看起来像这样(为了表示/视觉上的方便,使用名为...的谓词):

Using a DCG, it would look like this (using a predicate named ... for notational/visual convenience):

before(X, Y) --> ..., [X], ..., [Y], ... .
... --> [].
... --> [_], ... .

| ?- phrase(before(X, Y), [a,b,c]).

X = a
Y = b ? ;

X = a
Y = c ? ;

X = b
Y = c ? ;

(1 ms) no

如果愿意,可以将其包装在谓词中

And you can wrap it in a predicate, if you wish:

before(X, Y, L) :- phrase(before(X, Y), L).


正如@CapelliC所指出的,如果在列表中至少有一个 XY之前,则上述谓词成功.但是,如果定义是 X在列表中的Y之前,那么另一种DCG实现可以是:


As @CapelliC points out, the above predicate succeeds if there is at least one case in the list in which X comes before Y. However, if the definition is, X is seen before Y in the list, then an alternative DCG implementation could be:

before(X, Y) --> anything_but(Y), [X], ..., [Y], ... .

anything_but(_) --> [].
anything_but(Y) --> [X], { dif(X, Y) }, anything_but(Y).

... --> [].
... --> [_], ... .

这将导致:

| ?-  phrase(before(X,Y), [b,a,b]).

X = b
Y = b ? a

X = a
Y = b

no

这篇关于Prolog,列表中Y之前的X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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