Reputation: 13
I am struggling to get my head around Prolog lists.
Here's my problem: I need to take in a list and two variables and store the odd elements in list A and the even elements in list B.
I got this but its not giving the results im looking for
store(X, [], []).
store([X,Y|Z],[X|_],[Y|_]):-store(Z,X,Y).
Result should be:
where ?- store ([a,b,c,1,2,3], A, B).
A = [b,1,3].
B = [a,c,2].
Upvotes: 1
Views: 1649
Reputation: 60034
to build additional lists from a list argument do a recursive visit of it, storing elements where appropriate. See if you can complete this snippet
odd_even([], [], []).
odd_even([N|Ns], [N|Odds], Evens) :-
odd(N),
!, odd_even(Ns, Odds, Evens).
% here another odd_even for evens
odd(N) :-
... % use rem/2 to find the integer remainder of N is 1
edit: to move elements from even places in a list and elements at odd places in another (usually called a split), the visit just places them on two additional arguments: we need one more termination rule, because now we consider two arguments together from the list to be splitted.
split([], [], []).
split([X], [], [X]).
split([X,Y|R], [X|Xs], [Y|Ys]) :-
split(R,Xs,Ys).
there is a case to consider: if odd vs even must be 'counted' from the end of list. Then we should swap (eventually) the lists when done...That would require to add 2 more arguments to the recursive visit, or count the num.of.elements to decide beforehand where to aplce them...
Upvotes: 1