Search code examples
listprologreverse

Calculating List of positive numbers of a given list in Prolog


I tried resolving it by myself in the following way:

list_of_positives(L1, L2) :- 
   list_of_positives(L1, L2, []).
list_of_positives([], L, L).
list_of_positives([H|T], L2, L3) :- 
   (   H > 0 
   ->  list_of_positives(T,L2,[H|L3])
   ;   list_of_positives(T,L2,L3) 
   ).

The problem with this solution is that I get as response a reversed list of positive numbers. Can someone help me to find a way to get the list in the "correct order"?


Solution

  • You can solve the problem as follows:

    positives([], []).
    
    positives([H|T], P) :-
       (   H > 0
       ->  P = [H|R]     % desired order!
       ;   P = R),
       positives(T, R) .
    

    Example:

    ?- positives([2,-3,6,-7,1,4,-9], P).
    P = [2, 6, 1, 4].