superluigisunshine
superluigisunshine

Reputation: 41

Why does my prolog predicate only work with an even number of elements in its list?

My predicate eo is supposed to function as so,

?- eo([a,b,c,d,e,f],L).

L = [b,d,f]

My code right now is,

eo([], []).
eo([_,X|L], [X | R]) :-
    eo(L, R).

But it only works when the given list as an even number of elements. When given a list with an odd number of elements, it just outputs false. Any advice?

EDIT:

?- eo([a,b,c,d,e,f,g],L).

L = [b,d,f]

is the expected results for an odd number of elements in the list.

Upvotes: 1

Views: 73

Answers (2)

Paulo Moura
Paulo Moura

Reputation: 18663

QuickCheck can help no only in finding failing queries for buggy predicates but also narrow down those failing queries to the most simple one. In this case, using Logtalk's lgtunit tool QuickCheck support:

?- lgtunit::quick_check(eo(+list(character), -list(character))).
*     quick check test failure:
*       eo([d],[])
false.

Comparing the failing query to your code, makes it clear the bug pointed out in the (other) answers and the comments: no clause for handling an input list with a single element.

But do remember that QuickCheck generates random test queries and thus is only able to show a failing query, not proving correctness.

Upvotes: 0

EchoMike444
EchoMike444

Reputation: 1692

This solution is working

eo([],[]).
eo([_],[]).
eo([_,X|L],[X|R]) :- eo(L,R).

You need to have the second line that handle the list of one element ,

Upvotes: 1

Related Questions