'Prolog: Find positve numbers in a given list

I would like to know how to find a sublist of positive numbers in a given list L, example:

L = [-1, 5, 3, -7, 10]

Sublist = [5, 3, 10]

I tried:

pos_sublist([], []).
pos_sublist(H|L, LO) :- H>=0, pos_sublist(L, H|LO).

How could I implement the recursion part?



Solution 1:[1]

You need to read up on list notation (for which, see my answer to the question "https://stackoverflow.com/questions/24043039/accessing-list-elements-in-a-list-of-lists-in-prolog-to-operate-on".

Since you are omitting the [...] square brackets, you no longer have lists: you just have the [nested] data structure '|'/2.

The easiest way to select non-negative (positive meaning 'greater than zero', as zero does not have a sign) values from a list is a combination of member/2 and findall/3:

positive_nums(Xs,Ps) :- findall(P, (member(P,Xs), P >= 0), Ps ) .

Rolling your own, though, isn't much more complex:

positive_nums( []     , []     ) .
positive_nums( [X|Xs] , [X|Ys] ) :- X >= 0, !, positive_nums(Xs,Ys) .
positive_nums( [_|Xs] ,    Ys  ) :-            positive_nums(Xs,Ys) .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicholas Carey