I want to write a code in prolog that gets a list and find its positive numbers and adds them into a new list as below :
?- findPositives([-1,2,3,-5,-7,9],Result)
Result : [2,3,9]
How can I write this code?
Using tfilter/3
:
positive_truth(N, true) :-
N >= 0.
positive_truth(N, false) :-
N < 0.
?- tfilter(positive_truth, [-1,2,3,-5,-7,9],Result).
Result = [2,3,9].
Alternatively, using library(clpfd)
:
pos_truth(Expr, Truth) :-
Expr #>= 0 #<==> Bool,
bool01_truth(Bool, Truth).
bool01_truth(0,false).
bool01_truth(1,true).
?- tfilter(pos_truth, [-1,2,3,-5,-7,9],Result).
Result = [2,3,9].
?- tfilter(pos_truth, [X,Y],Result).
Result = [], X in inf.. -1, Y in inf.. -1
; Result = [Y], X in inf.. -1, Y in 0..sup
; Result = [X], X in 0..sup, Y in inf.. -1
; Result = [X, Y], X in 0..sup, Y in 0..sup.