序言:在列表中,在给定元素之后查找元素 [英] Prolog: In a list, finding the element after a given element
问题描述
我最近开始在Prolog中进行编程,目前正在尝试创建规则,以在列表中的给定元素之后找到该元素.例如,我希望find(2,X,[1,2,3,4]).
产生3
.
I recently began programming in Prolog and am currently trying to create rules that find the element after a given element in a list. For example, I want find(2,X,[1,2,3,4]).
to result in 3
.
到目前为止,我的尝试:
My attempt so far:
find(X,Y,[X,Y|Tail]):-
!.
find(X,Y,[_|Tail]):-
find(X,Y,Tail).
推荐答案
让我们使用if_/3
和(=)/3
(又名equal_truth/3
),如
Let's use if_/3
and (=)/3
(a.k.a. equal_truth/3
), as defined by @false in this answer!
因此,出现了新的逻辑上纯净的 find/3
:
find(E0,E1,[X|Xs]) :-
member_next_prev_list(E0,E1,X,Xs).
member_next_prev_list(E0,E1,X0,[X1|Xs]) :-
if_(X0=E0, X1=E1, member_next_prev_list(E0,E1,X1,Xs)).
让我们运行OP提到的查询/其他答案/一些评论:
Let's run the queries mentioned by the OP / by other answers / by some comments:
?- find(a,X,[a,a,b]).
X = a. % succeeds deterministically
?- find(a,X,[a,Y,b]).
X = Y. % succeeds deterministically
?- find(a,b,[a,a,b]).
false. % fails
?- find(a,X,[a,a,b,c]).
X = a. % succeeds deterministically
?- find(b,X,[a,a,b,c]).
X = c. % succeeds deterministically
现在有了一些更小的内容:
?- find(X,Y,[a,a,b,c]).
X = a, Y = a ;
X = b, Y = c ;
false.
最普遍的查询如何?由于代码是纯的,因此我们得到合理的答案:
What about the most general query? As the code is pure, we get logically sound answers:
?- find(X,Y,List).
List = [ X,Y|_Z] ;
List = [_A, X,Y|_Z], dif(_A,X) ;
List = [_A,_B, X,Y|_Z], dif(_A,X), dif(_B,X) ;
List = [_A,_B,_C, X,Y|_Z], dif(_A,X), dif(_B,X), dif(_C,X) ;
List = [_A,_B,_C,_D,X,Y|_Z], dif(_A,X), dif(_B,X), dif(_C,X), dif(_D,X) ...
编辑2015-05-06
这是一个更简洁的变体,简称为findB/3
:
Edit 2015-05-06
Here's a more concise variant, unimaginatively called findB/3
:
findB(E0,E1,[X0,X1|Xs]) :-
if_(X0=E0, X1=E1, findB(E0,E1,[X1|Xs])).
就像find/3
一样,findB/3
在不留下无用的选择点的意义上很有效,但它具有更高的内存使用率.
Like find/3
, findB/3
is efficient in the sense of not leaving useless choicepoints behind, but it has higher memory use.
findC/3
尝试通过提升公共表达式[X1|Xs]
来减少内存使用:
findC/3
tries to reduce the memory use by hoisting the common expression [X1|Xs]
:
findC(E0,E1,[X0|XXs]) :-
XXs = [X1|_],
if_(X0=E0, X1=E1, findC(E0,E1,XXs)).
这篇关于序言:在列表中,在给定元素之后查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!