如何表示“左侧某处”?在序言中?

发布于 2024-12-14 01:26:38 字数 83 浏览 2 评论 0原文

在Prolog中,如何表示“左侧某处”的情况。 例如,有一个List“List”和两个术语“X”和“Y”,如何表示规则:X在List中位于Y左侧的某处。

In the Prolog, how to represent the situation "somewhere to the left".
For example, there is a List "List" and two terms "X" and "Y", how to represent the rule: X is somewhere to the left of Y in the List.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

怀念你的温柔 2024-12-21 01:26:38

这可以简化为子序列匹配的问题。

subsequence([], _).
subsequence([X|Sub], [X|Seq]) :-
    subsequence(Sub, Seq).
subsequence(Sub, [_|Seq]) :-
    subsequence(Sub, Seq).

那么你的“left-of”查询将是subsequence([X, Y], List), !

This can be reduced to the problem of subsequence matching.

subsequence([], _).
subsequence([X|Sub], [X|Seq]) :-
    subsequence(Sub, Seq).
subsequence(Sub, [_|Seq]) :-
    subsequence(Sub, Seq).

Then your "left-of" query would be subsequence([X, Y], List), !.

韬韬不绝 2024-12-21 01:26:38

您想要描述列表的一些属性。语法通常是解决这个问题的最佳方法。

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

?- Xs = "abc", phrase((...,[X], ..., [Y], ...), Xs).
   Xs = "abc", X = a, Y = b
;  Xs = "abc", X = a, Y = c
;  Xs = "abc", X = b, Y = c
;  false.

You want to describe some properties of lists. Grammars are often the best way to address this.

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

?- Xs = "abc", phrase((...,[X], ..., [Y], ...), Xs).
   Xs = "abc", X = a, Y = b
;  Xs = "abc", X = a, Y = c
;  Xs = "abc", X = b, Y = c
;  false.
只是我以为 2024-12-21 01:26:38

它可以通过多种方式完成。
nth1(N,List,X) 是一个谓词,如果 List 的第 N 个元素是 X,则该谓词为 true。

使用 nth1 的实现非常简单;在你看到我的代码之前尝试解决它。

left(X,Y,L):-
    nth1(NX,L,X),
    nth1(NY,L,Y),
    NX<NY.

解决这个问题的其他方法是使用append/3:

left(X,Y,L):-
   append(_,[X|T],L),
   member(Y,L).

或者只是简单的递归:

left(X,Y,[X|T]):-
   member(Y,T).
left(X,Y,[H|T]):-
   H=\=X,
   left(X,Y,T).

it can be done in many ways.
nth1(N,List,X) is a predicate that is true if the Nth element of the List is X.

The implementation using nth1 is pretty easy; try to solve it before you see my code.

left(X,Y,L):-
    nth1(NX,L,X),
    nth1(NY,L,Y),
    NX<NY.

Other ways to solve it is with append/3:

left(X,Y,L):-
   append(_,[X|T],L),
   member(Y,L).

or just plain recursion:

left(X,Y,[X|T]):-
   member(Y,T).
left(X,Y,[H|T]):-
   H=\=X,
   left(X,Y,T).
九局 2024-12-21 01:26:38

如果你已经有了append/3谓词那么你可以使用:

left(A,B,S) :-
    append(_,[B,A|_],S).

如果你问:

?- left(1,2,[1,2,3,4]).
false.

?- left(2,1,[1,2,3,4]).
true

-Leo

If you already have the append/3 predicate then you can use:

left(A,B,S) :-
    append(_,[B,A|_],S).

If you ask:

?- left(1,2,[1,2,3,4]).
false.

?- left(2,1,[1,2,3,4]).
true

-Leo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文