gpt4 book ai didi

list - 如何删除所有出现的情况?

转载 作者:行者123 更新时间:2023-12-03 08:56:20 25 4
gpt4 key购买 nike

我试图理解为什么代码 1 工作正常但代码 2 输出错误:

remove(X,[],[]).
remove(X,[X|Y],Z):-remove(X,Y,Z). % [X|Y] is the input list
remove(X,[F|Y],[F|Z]):-remove(X,Y,Z). % code 1


remove(X,[],[]).
remove(X,[X|Y],Z):-remove(X,Y,Z). % [X|Y] is the input list
remove(X,[F|Y],Z):-remove(X,Y,[F|Z]). % code 2

最佳答案

您提出的两个谓词 - 代码 1 代码 2 - 均已损坏。

您没有注意到这一点的原因是:查询


#1)考虑 this previous "answer" 中显示的查询:

?- remove(x, [x,a,b,c,x,d], R).R = [a,b,c,d]                      % okay

Okay? Yes, but there may be more answers. Let's press ;!

;  R = [a,b,c,x,d]                 % BAD!;  R = [x,a,b,c,d]                 % BAD!;  R = [x,a,b,c,x,d]               % BAD!;  false.                          % (no more answers)

These three answers are invalid, as each R contains some x.

The bottom like: Don't just look at some query answers. Look at all query answers!


#2)Prolog programs comprise different kinds of clauses: facts, rules, and queries.

Queries are a very—if not the most—important part of your program.

Queries are both documentation and specification. Most importantly, they enable you to delegate the "mechanical" part of program development to the Prolog processor.

So which queries to write?

  • Start with the most general query:

    ?- remove(A,B,C).

  • Queries you expect to succeed:

    ?- remove(x,[x,a,x,p],[a,p]).   % x is first element
    ?- remove(x,[a,x,p,x],[a,p]). % x is last element
    ?- remove(x,[a,x,p],[a,p]).
  • 您预计会失败的查询

    ?- \+ (remove(x,[a,x,p],Ls), dif(Ls,[a,p])).
  • 地面查询:

    ?- remove(x,[],[]).
  • 非基础查询(带变量的查询):

    ?- remove(X,[a,b,a,c,d,c,a,b],Xs).

底线:如果没有查询,您就不是在编写代码,您只是在编写文本。


#3)现在让我们开始修复代码 1:看看两个递归子句!

remove(X,[X|Y],Z) :- remove(X,Y,Z).remove(X,[F|Y],[F|Z]) :- remove(X,Y,Z).

第一条规则将 X 与第一个列表 [X|Y] 相关。好的!

第二条规则不将 X[F|Y][F|Z] 结合使用。糟糕!

通过添加目标 dif/2 到第二个子句,我们可以建立该连接。


#4)完成!以下是谓词 remove/3 的完整代码:

remove(_X, [], []).remove(X, [X|Y], Z) :-   remove(X, Y, Z).remove(X, [F|Y], [F|Z]) :-   dif(X, F),   remove(X, Y, Z).

关于list - 如何删除所有出现的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55024920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com