Reputation: 41
This is the code that i've made and it should split the list in three other lists and in the first list there should be negative numbers, in the second list even numbers and in the third list odd numbers.
functie([],_,_,_).
functie([H|T],Neg,Odd,Even):-
((H<0) , append(Neg,[H],Neg1) , functie(T,Neg1,Odd,Even)) ;
(((H rem 2)=:=1), append(Odd,[H],Odd1) , functie(T,Neg,Odd1,Even)) ;
(((H rem 2)=:=0), append(Even,[H],Even1) , functie(T,Neg,Odd,Even1)).
Upvotes: 3
Views: 271
Reputation: 60004
to learn, it's better to implement from scratch, but actually, there are libraries to handle most common tasks
functie(L,N,O,E) :-
partition(>=(0),L,T,N),
partition(odd,T,O,E).
odd(N) :- 1 =:= N mod 2.
Upvotes: 0
Reputation: 726489
Assuming that odd and even lists are for non-negative numbers only, you could do the split using a four-clause predicate. The base clause should deal with an empty list, providing empty results. The remaining three clauses should deal with three conditions - namely, when the head is negative, when the head is odd, and when the head is even.
The result is pretty straightforward: the three clauses have identical structure; their only difference is the condition before the recursive invocation, and the list to which the head element is added in the header.
split([],[],[],[]).
split([H|T], [H|Ntail], Odd, Even) :- H < 0, split(T, Ntail, Odd, Even).
split([H|T], Neg, [H|Otail], Even) :- H >= 0, ((H rem 2)=:=1), split(T, Neg, Otail, Even).
split([H|T], Neg, Odd, [H|Etail]) :- H >= 0, ((H rem 2)=:=0), split(T, Neg, Odd, Etail).
Note that this implementation does not use any of Prolog's library predicates. Everything is done through unification.
Upvotes: 1