Splitting a list of integers into a list of positive integers and a list of negative integers

The recursive part is not quite correct.

split([], [], []).
split([Head|Tail], [Head|List1], List2) :- Head>=0, split(Tail, List1, List2).
split([Head|Tail], List1, [Head|List2]) :- Head<0, split(Tail, List1, List2).

The Head should be added to the positive list if Head >= 0 and to the negative list when Head < 0.

Moreover, checking the sign of Head at the beginning is better, because it will prevent unnecessary recursive calls.

Leave a Comment