I have the following code:
pick_even([], []).
pick_even([_, H | T], [H | R]) :-
pick_even(T, R).
pick_even([_, H , _ | T], [H | R]) :-
pick_even(T, R).
When running the query, ?- pick_even(L,[4,7]).
, I want to receive the output:
L = [_7650, 4, _7662, 7] ;
L = [_7650, 4, _7662, 7, _7674] ;
Instead I am receiving some extra outputs that I do not want:
L = [_7650, 4, _7662, 7] ;
L = [_7650, 4, _7662, 7, _7674] ;
L = [_7650, 4, _7662, _7668, 7] ;
L = [_7650, 4, _7662, _7668, 7, _7680].
How can I eliminate these extra outputs without modifying the query?
I'm brand new to prolog, so I expect this to be a very easy syntax fix.
list_evens([], []).
list_evens([_|Es], Fs) :-
list_evens2(Es, Fs).
list_evens2([], []).
list_evens2([E|Es], [E|Fs]) :-
list_evens(Es, Fs).
That is, you forgot in particular the case of a one-element list.
And, for testing, the best way is to take the most general query:
?- list_even(Xs, Ys).
Xs = [], Ys = []
; Xs = [_A], Ys = []
; Xs = [_A,_B], Ys = [_B]
; Xs = [_A,_B,_C], Ys = [_B]
; Xs = [_A,_B,_C,_D], Ys = [_B,_D]
; Xs = [_A,_B,_C,_D,_E], Ys = [_B,_D]
; Xs = [_A,_B,_C,_D,_E,_F], Ys = [_B,_D,_F]
; ... .
In this manner you say:
Oh Prolog, why should I figure out what cases are of interest? Please do this for me!
And, diligently, Prolog will fill out the blanks. So you only need to ensure that all the answers you expect are here.