我在Prolog中有两个稍微不同的谓词unique_element/2实现.当给定元素X和列表L时,谓词成功,元素X在列表中仅出现一次.以下是实现和结果:
实施1:
%%% unique_element/2
unique_element(Elem, [Elem|T]) :-
not(member(Elem, T)).
unique_element(Elem, [H|T]) :-
member(Elem, T),
H\==Elem,
unique_element(Elem, T),
!.
Run Code Online (Sandbox Code Playgroud)
结果:
?- unique_element(X, [a, a, b, c, c, b]).
false.
?- unique_element(X, [a, b, c, c, b, d]).
X = a ;
X = d.
Run Code Online (Sandbox Code Playgroud)
实施2:
%%% unique_element/2
unique_element(Elem, [Elem|T]) :-
not(member(Elem, T)).
unique_element(Elem, [H|T]) :-
H\==Elem,
member(Elem, T),
unique_element(Elem, T),
!.
Run Code Online (Sandbox Code Playgroud)
如果你没有第一眼就注意到:"H\== Elem"和"成员(Elem,T)"在第二个impl,规则2上被翻转.
结果:
?- unique_element(X, [a, a, b, c, c, b]).
X = a.
?- unique_element(X, [a, b, c, c, …Run Code Online (Sandbox Code Playgroud) prolog ×1