为什么我删除了想要的号码列表后,又为什么要重新获得原件?

编程入门 行业动态 更新时间:2024-10-16 19:23:44
本文介绍了为什么我删除了想要的号码列表后,又为什么要重新获得原件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试实施一个序言规则,该规则将从某个列表中删除数字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.

更多推荐

为什么我删除了想要的号码列表后,又为什么要重新获得原件?

本文发布于:2023-11-01 01:55:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1547908.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原件   又为   号码   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!