在prolog中从列表中过滤掉大量数字

时间:2010-12-06 23:29:44

标签: prolog

我想编写一个函数,通过删除小于或等于特定数字的所有内容来过滤数字列表。该功能将采用两个参数:数字列表和要过滤的数字。该函数应返回一个列表,其中所有数字都大于过滤器编号。

有时这样:

filter_num_list(L1,N,L2) :- ...

test_filter_num_list :- filter_num_list([1,2,3,4,5,6,7,8,9],5,[5,6,7,8,9]).

3 个答案:

答案 0 :(得分:5)

另请参阅库谓词,例如include / 3和exclude / 3:

?- include(=<(5), [1,2,3,4,5,6,7,8,9], Is).
Is = [5, 6, 7, 8, 9].

答案 1 :(得分:2)

使用 tfilter/3和具体化的约束(#<)/3,您可以跟上并立即表达您想要的内容!

:- use_module(library(clpfd)).

这是我使用SWI-Prolog版本7.1.37运行的查询:

?- tfilter(#<(5),[1,2,3,4,5,6,7,8,9],Xs).
Xs = [6,7,8,9].                             % succeeds deterministically
false.

由于代码单调,我们还可以提出更一般的查询并获得逻辑上合理的答案。

?- tfilter(#<(7),[A,B,C],Xs).
Xs = [],      A in inf..7, B in inf..7, C in inf..7 ;
Xs = [C],     A in inf..7, B in inf..7, C in 8..sup ;
Xs = [B],     A in inf..7, B in 8..sup, C in inf..7 ;
Xs = [B,C],   A in inf..7, B in 8..sup, C in 8..sup ;
Xs = [A],     A in 8..sup, B in inf..7, C in inf..7 ;
Xs = [A,C],   A in 8..sup, B in inf..7, C in 8..sup ;
Xs = [A,B],   A in 8..sup, B in 8..sup, C in inf..7 ;
Xs = [A,B,C], A in 8..sup, B in 8..sup, C in 8..sup ;
false.

答案 2 :(得分:1)

尝试类似:

filter_num_list([],N,[]) :- true.  
filter_num_list([H|T],N,[H|S]) :- H > N,filter_num_list(T,N,S).  
filter_num_list([H|T],N,S) :- N >= H, filter_num_list(T,N,S).