I'm trying to split a list into two other list. List Even with the elemnts in even possition and a List Odd with the others. I've been looking over iinternet a solution, but all seem to me like chinese, i can not understand the process. So this is what i've been trying:
but the only return i got is something like Oddlist = _7132946 Evenlist = _26997888.
I don't know what i'm doing wrong. I'll apreciate any help. Thank you!
Best How To :
The answer by CapelliC is perfect. Just to explain:
When you have a Prolog clause like this:
foo([H|T], [H|Z]) :-
which you then call like this:
?- foo([a,b,c], L).
from: foo([H| T ], [H|Z]) with H = a, T = [b,c], L = [a|Z]
call: foo([a|[b,c]], [a|Z])
which then leads to the recursive call:
call: foo([b,c], Z).
from: foo([H| T ], [H|Z]) with H = b, T = [c], L = [b|Z]
call: foo([b|[c]], [b|Z])
At this point, the list that you made at the beginning,
[a|Z] is now
[a|[b|Z]], which is
So, you create a list in the variable passed as the second argument, and stick H at the front of the list. The rest of the list you give to the recursive call. You will keep adding elements to the end of the list until the first list is the empty list. At that point, you will have end the new list, too:
In your example, there is another predicate mutually recursive with the first one:
foo(, , ).
foo([H|T], [H|F], B) :-
bar(T, F, B).
bar(, , ).
bar([H|T], F, [H|B]) :-
foo(T, F, B).
Of course, this will "unzip" a list into two lists.