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]).
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].
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With