1
votes

So I'm trying to get list of positive elements from given list. So far I've come to this solution:

1 getPos([],[]).
2 getPos([], L).
3 getPos([Head|Tail], L):-
4   Head<0, getPos(Tail,L).
5 getPos([Head|Tail], L:-
6   Head>0, getPos(Tail, [Head|L]).

If I try getPos([1,-2,3], Result). I get to fact number 2 with this result:

Call: getPos([], [3,1|_29])?
Exit: getPos([], [3,1|_29])?

After that I just quit out of recursion and end up with only "yes" answer. My 2 quesstions are:
1. What should I do, so my program would stop at that 2nd fact and just return value of L
2. Is it possible to keep order of source list? (my version reverses source list)

1

1 Answers

3
votes

You should use a third argument getPos(In, CurOut, Out), and when In is empty (e.g. [], you unify CurOut with Out. so you get

getPos(In, Out) :-
    getPos(In, [], Out).
getPos([],L, L).
% getPos_1([], L).
getPos([Head|Tail], CurL, L):-
   Head<0, getPos(Tail,CurL, L).
getPos([Head|Tail], CurL, L):-
   Head>0, getPos(Tail, [Head|CurL], L).

What do you do if a value is 0 ?

In SWI-Prolog you can use include/3

get_pos(In, Out) :-
    include(>( 0), In, Out).

If you want to only use 2 args you can write

getPos1([], []).
getPos1([Head|Tail], L):-
   Head<0, getPos1(Tail,L).
getPos1([Head|Tail], [Head|L]):-
   Head>0, 
   getPos1(Tail, L).