Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out large number from list in prolog

Tags:

prolog

I want to write a function which filters a list of numbers by removing everything less than or equal to a specific number. The function will take two parameters: a list of numbers and the number to filter. The function should returns a list which has all the numbers larger than the filter number.

Sometime like this:

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]).
like image 662
Corey Avatar asked Dec 06 '10 23:12

Corey


3 Answers

See also library predicates like include/3 and exclude/3:

?- include(=<(5), [1,2,3,4,5,6,7,8,9], Is).
Is = [5, 6, 7, 8, 9].
like image 143
mat Avatar answered Nov 04 '22 03:11

mat


With meta-predicate tfilter/3 and the reified clpfd constraint (#<)/3, you can keep up logical-purity and express what you want in no time!

:- use_module(library(clpfd)).

Here's a query that I ran with SWI-Prolog version 7.1.37:

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

As the code is monotone, we can also ask more general queries and get logically sound answers.

?- 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.
like image 41
repeat Avatar answered Nov 04 '22 05:11

repeat


try something like:

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).
like image 33
yurib Avatar answered Nov 04 '22 05:11

yurib