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

查看:8
本文介绍了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 指出的那样,如果列表中X 位于Y 之前的至少一种情况,则上述谓词成功.但是,如果定义是,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天全站免登陆