如果项目不在列表(prolog)中,则返回false

发布于 2025-01-24 07:10:27 字数 503 浏览 0 评论 0原文

以下是如果在那里,则从列表中删除键(a)的代码。如果不存在,它当前将返回整个列表。我希望它能返回“ false”。样本输出也将低于下方。

mySelect(_, [], []).
mySelect(X, [Y|K], [Y|M]):- mySelect(X, K, M), (X \= Y).
mySelect(X, [X|K], R) :- mySelect(X, K, R).

目前,这将输出:

?- my_delete(c,[a,b,c,d],R). 
R = [a, b, d] .

?- my_delete(e,[a,b,c,d],R). 
R = [a, b, c, d] .

我希望它输出:

?- my_delete(c,[a,b,c,d],R). 
R = [a, b, d] .

?- my_delete(e,[a,b,c,d],R). 
false .

任何指针都将不胜感激!

Below is the code to remove a key (A) from a list if it is there. If it isn't there, it currently returns the entire list. I would like it instead to return 'false.' Sample outputs will be below as well.

mySelect(_, [], []).
mySelect(X, [Y|K], [Y|M]):- mySelect(X, K, M), (X \= Y).
mySelect(X, [X|K], R) :- mySelect(X, K, R).

Currently this will output:

?- my_delete(c,[a,b,c,d],R). 
R = [a, b, d] .

?- my_delete(e,[a,b,c,d],R). 
R = [a, b, c, d] .

I would like it to output:

?- my_delete(c,[a,b,c,d],R). 
R = [a, b, d] .

?- my_delete(e,[a,b,c,d],R). 
false .

Any pointers would be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

计㈡愣 2025-01-31 07:10:27

您可以添加另一个规则,该规则首先确保X是L的成员,然后再应用MySelect

delete(X, L, R) :-  member(X, L), mySelect(X, L, R).

You can add another rule which first ensures that X is a member of L, before applying mySelect.

delete(X, L, R) :-  member(X, L), mySelect(X, L, R).
思念满溢 2025-01-31 07:10:27

将列表分为匹配和非匹配:

filter( X , Ys, Zs ) :- filter(X,Ys,[_|_],Zs).

filter( _ ,    []  ,    []  ,    []  ) .
filter( X , [X|Ys] , [X|Xs] ,    Zs  ) :- !, filter(X,Ys,Xs,Zs) .
filter( X , [Y|Ys] ,    Xs  , [Y|Zs] ) :-    filter(X,Ys,Xs,Zs) . 

或计数项目数,并测试计数大于零:

filter( X , Ys, Zs ) :- filter(X,Ys,0,N,Zs), N > 0 .

filter( _ ,    []  , N , N ,    []  ) .
filter( X , [X|Ys] , T , N ,    Zs  ) :- T1 is T+1, !, filter(X,Ys,T1,N, Zs) .
filter( X , [Y|Ys] , T , N , [Y|Zs] ) :-            !, filter(X,Ys,T,N,Zs) .

Either partition the list into matches and non-matches:

filter( X , Ys, Zs ) :- filter(X,Ys,[_|_],Zs).

filter( _ ,    []  ,    []  ,    []  ) .
filter( X , [X|Ys] , [X|Xs] ,    Zs  ) :- !, filter(X,Ys,Xs,Zs) .
filter( X , [Y|Ys] ,    Xs  , [Y|Zs] ) :-    filter(X,Ys,Xs,Zs) . 

or count the number of items and test the count for being greater than zero:

filter( X , Ys, Zs ) :- filter(X,Ys,0,N,Zs), N > 0 .

filter( _ ,    []  , N , N ,    []  ) .
filter( X , [X|Ys] , T , N ,    Zs  ) :- T1 is T+1, !, filter(X,Ys,T1,N, Zs) .
filter( X , [Y|Ys] , T , N , [Y|Zs] ) :-            !, filter(X,Ys,T,N,Zs) .
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文