如何删除列表中可以除以3的所有元素(即x % 3 == 0
)?
答案 0 :(得分:2)
这是一个谓词removemod(+ List,+ Mod,?Result):
removemod([],_,[]).
removemod([H|T],M,[H|T2]):-
H mod M =\= 0,
removemod(T,M,T2).
removemod([H|T],M,T2):-
H mod M =:= 0,
removemod(T,M,T2).
似乎工作:
15 ?- removemod([3,7,5,12,8,2,16,13,9,11,27],3,L).
L = [7, 5, 8, 2, 16, 13, 11] .
16 ?- removemod([66933],3,L).
L = [].
答案 1 :(得分:2)
执行此操作的惯用方法是使用更高的顺序,例如,在SWI中,有一个名为exclude/3
的好谓词可以完全按照您的意愿执行(删除基于谓词的元素):
clean(List, FilteredList) :-
exclude(mod3, List, FilteredList).
mod3(X) :-
X mod 3 =:= 0.
更高的顺序与lambda library:
相比更为分类:- use_module(lambda).
filterMod3(List, FilteredList) :-
exclude(\X^(X mod 3 =:= 0), List, FilteredList).
答案 2 :(得分:0)
或更简单的findall(X,(member(X,[1,2,3,4,5,6,7,8,9,10]),0 =:= X mod 3),Y).