enneenne
enneenne

Reputation: 219

Prolog - list contains 2x element X

Let's assume we have alphabet {x,y} and I want to create a function, which returns true or false, whether the input list contains 2x symbol x after each other.

For example two([x,x,y]). returns true, while two([x,y,x]). returns false.

This is my function that I have so far:

two([Xs]) :- two(Xs, 0).
two([y|Xs], S) :- two(Xs, S).
two([x|Xs], S) :- oneX(Xs, S).
two([], S) :- S=1.

oneX([x|Xs], S) :- S1 is 1, two(Xs, M1).
oneX([y|Xs], S) :- two(Xs, S).

I use parameter S to determine, whether there were 2x x already (if so, parameter is 1, 0 else). This function however doesn't work as intended and always return false. Can you see what am I doing wrong?

Upvotes: 2

Views: 42

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You can use unification here and thus check if you can unify the first two items of the list with X, if not, you recurse on the list:

two([x, x|_]).
two([_|T]) :-
    two(T).

The first clause thus checks if the first two items of the list are two consecutive xs. The second clause recurses on the tail of the list to look for another match by moving one step to the right of the list.

Upvotes: 3

Related Questions