从列表中取出偶数
定义规则filterevens(LST0, LST1)。该规则描述了列表LST0如何与列表LST1相关,列表LST1仅由LST0的偶数元素组成。
我需要从列表中选取偶数,我得到了这个:
filterevens([],[]).
filterevens([H|T],R):-
( 0 is mod(H,2)
-> R = [H|T2]
; R = T2
),
filterevens(T,T2).
当输入时
?- filterevens( [2,4] ,A).
它可以给我正确的答案。但如果我尝试
?- filterevens(A,[2,4]).
它会导致错误。那么我应该怎么做才能在一条规则中同时完成这两项任务呢?
Define the rule filterevens(LST0, LST1). This rule describes how the list LST0 relates to the list LST1, which consists of only even elements of LST0.
I need to pick up the even numbers from a list, And I got this:
filterevens([],[]).
filterevens([H|T],R):-
( 0 is mod(H,2)
-> R = [H|T2]
; R = T2
),
filterevens(T,T2).
when the input is
?- filterevens( [2,4] ,A).
it can give me the correct answer. But if I tried
?- filterevens(A,[2,4]).
it cause an error. So what should I do so that I can do both in just one rule?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在没有
;
的情况下完整地写出这些情况就足以使其在基本情况下工作:那么:
一般情况下,
A
可以是任何长度[1, 2,1,4]
或[1,1,1,1,1,2,4]
,使用2
、4
因为只有偶数会更困难。如果您可以限制列表的成员,例如“1 到 1,000 之间的正整数”,您可以使用 clpfd 库构建一些东西。Writing the cases out in full without
;
is enough for it to work in the basic case:Then:
The general case,
A
could be any length[1,2,1,4]
or[1,1,1,1,1,2,4]
, generating all possible lists with2
,4
as the only even numbers would be more difficult. You could build something with theclpfd
library if you could constrain the members of the list, e.g. to "positive integers between 1 and 1,000".