序言:第一个重复值 [英] Prolog: First duplicate value
问题描述
我需要在列表中找到第一个重复的值.
I need to find the first duplicate value in a list.
prep(3,[1,3,5,3,5]).
应该为真.
prep(5,[1,3,5,3,5]).
应该为假.
我想检查与当前值和以前的列表成员是否相等,直到找到一个重复项,如果找到一个重复项,它将测试与X的相等性,但是我不知道如何在Prolog中做到这一点!
I thought checking for equality with the current value and the previous list members until I find a duplicate, if it finds one it will test for equality with X but I have no idea how to do that in Prolog!
我非常感谢您的帮助!谢谢
I appreciate any help! Thanks
推荐答案
这里是使用dif/2
的纯版本,该版本实现了声音不平等. dif/2
由B-Prolog,YAP-Prolog,SICStus-Prolog和SWI-Prolog提供.
Here is a pure version using dif/2
which implements sound inequality. dif/2
is offered by B-Prolog, YAP-Prolog, SICStus-Prolog and SWI-Prolog.
firstdup(E, [E|L]) :-
member(E, L).
firstdup(E, [N|L]) :-
non_member(N, L),
firstdup(E, L).
member(E, [E|_L]).
member(E, [_X|L]) :-
member(E, L).
non_member(_E, []).
non_member(E, [F|Fs]) :-
dif(E, F),
non_member(E, Fs).
优点是它还可以与更通用的查询一起使用:
The advantages are that it can also be used with more general queries:
?- firstdup(E, [A,B,C]).
E = A, A = B ;
E = A, A = C ;
E = C,
B = C,
dif(A, C) ;
false.
在这里,我们得到三个答案:A
是前两个答案中的重复项,但基于两个不同的理由:A
可能等于B
或C
.在第三个答案中,B
是重复项,但是只有C
与A
不同时,它才会是重复项.
Here, we get three answers: A
is the duplicate in the first two answers, but on two different grounds: A
might be equal to B
or C
. In the third answer, B
is the duplicate, but it will only be a duplicate if C
is different to A
.
要理解其定义,请以箭头←的形式阅读:-
.因此,右边是您所知道的,而左边是您所得出的结论.在开始时,朝该方向读取谓词通常会有些烦人,毕竟您可能会被诱惑遵循执行线程".但通常,此线程无处可寻-太复杂了,难以理解.
To understand the definition, read :-
as an arrow ← So what is on the right-hand side is what you know and on the left is what you conclude. It is often in the beginning a bit irritating to read predicates in that direction, after all you might be tempted to follow "the thread of execution". But often this thread leads to nowhere – it gets too complex to understand.
第一条规则如下:
提供的E
是列表L
的元素,我们得出结论,[E|L]
具有E
作为第一个重复项.
ProvidedE
is an element of listL
we conclude that[E|L]
hasE
as first duplicate.
第二条规则如下:
提供的E
是L
的第一个副本(在这里不要惊慌,说我们不知道...),并且前提是N
不是L
的元素,我们得出结论,[N|L]
具有E
作为第一个重复项.
ProvidedE
is the first duplicate ofL
(don't panic here and say we don't know that ...) and provided thatN
is not an element ofL
we conclude that[N|L]
hasE
as first duplicate.
许多Prolog系统中提供了member/2
谓词,可以将non_member(X,L)
定义为maplist(dif(X),L)
.因此,人们将firstdup/2
定义为:
The member/2
predicate is provided in many Prolog systems and non_member(X,L)
can be defined as maplist(dif(X),L)
. Thus one would define firstdup/2
rather as:
firstdup(E, [E|L]) :-
member(E, L).
firstdup(E, [N|L]) :-
maplist(dif(N), L),
firstdup(E, L).
这篇关于序言:第一个重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!