问题描述
我正在尝试实施一个序言规则,该规则将从某个列表中删除数字X并返回不包含X的列表.但是,在获得正确的结果之后,我也可以得到原始列表的替代结果,并且可以弄清楚代码中的问题出在哪里.
i was trying to implement a prolog rule which removes the number X from a certain list and returns the list without the X . However after getting the correct result i get as an alternative the original list as a result as well and i get figure out where is the problem in my code.
remove1(X,[],[]).
remove1(X,[X|T],T).
remove1(X,[H|T],[H|R]):-
X \= H,
remove1(X,T,R).
remove1(X,[H|T],[H|T]):-
\+member(X,T).
推荐答案
基本上,第一个和最后一个子句都是不必要的.最后一个子句是错误结果的出处.
Basically, the first and the last clause are unnecessary. The last clause is where the wrong results come from.
这似乎是另一个教科书"谓词,通常称为select/3
. [Sterling& Shapiro],第67页中的教科书定义与 SWI-Prolog库的实现,并执行以下操作:
This seems to be another "textbook" predicate, and it is usually called select/3
. The textbook definition in [Sterling&Shapiro], page 67, is identical to the SWI-Prolog library implementation and goes something like this:
%! select(?Elem, ?List1, ?List2)
%
% Is true when List1, with Elem removed, results in List2.
select(X, [X|Tail], Tail).
select(Elem, [Head|Tail], [Head|Rest]) :-
select(Elem, Tail, Rest).
您会注意到它不需要任何辅助谓词,并且是真实的关系.尝试例如:
You will notice that it does not need any helper predicates and is a true relation. Try for example:
?- select(X, [1,2,3], R).
甚至:
?- select(X, List, Rest), numbervars(List).
(numbervars/1
只是使解决方案更具可读性)
(numbervars/1
just makes the solutions a bit more readable)
此定义之所以是如此笼统,是因为……嗯,这是一个笼统的定义.第一个子句执行选择",第二个子句定义递归步骤.
This definition is as general as it is because... well, it is a general definition. The first clause does the "selecting", the second clause defines the recursive step.
[Sterling& Shapiro]:Sterling L,Shapiro EY. Prolog的艺术:先进的编程技术.麻省理工学院出版社; 1994.
[Sterling&Shapiro]: Sterling L, Shapiro EY. The art of Prolog: advanced programming techniques. MIT press; 1994.
这篇关于为什么我删除了想要的号码列表后,又为什么要重新获得原件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!