yihan li
yihan li

Reputation: 1

spilt list into to positive and negative lists in visual prolog

[-2,3,4,-6,7,-9, 10,12,13,-14,16,-17] In this list, how to spilt list into to positive and negative lists use visual prolog? Follow is my code, I just print positive or negative list, how to solve it?

enter image description here

Upvotes: 0

Views: 137

Answers (1)

brebs
brebs

Reputation: 4456

As an example of simple list processing:

split_list(PosNegLst, PosLst, NegLst) :-
    must_be(list, PosNegLst),
    split_list_(PosNegLst, PosLst, NegLst).
    
split_list_([], [], []).

split_list_([Head|Tail], PosLst, [Head|NegLst]) :-
    Head < 0, !,
    split_list_(Tail, PosLst, NegLst).

split_list_([Head|Tail], [Head|PosLst], NegLst) :-
    Head >= 0,
    split_list_(Tail, PosLst, NegLst).

Result in swi-prolog:

?- time(split_list([5, -2, -3, 6, 0, 8], PosLst, NegLst)).
% 21 inferences, 0.000 CPU in 0.000 seconds (89% CPU, 406677 Lips)
PosLst = [5,6,0,8],
NegLst = [-2,-3].

Upvotes: 1

Related Questions