Nobody
Nobody

Reputation: 103

Need help for programming a list in prolog

I want Prolog to return true only if the list is built with the letters {a,b} and if it has just one letter b or zero times the letter b and any amount of the letter a but the list empty is also true. For example :{} is true, {aaabaaa} is true, {a} or {b} is true, {baaaaa} is true. But {baaaab} is false, {bb} is false.

Here is what I tried to do, but it does not work as I want :

langage([]).

langage([a,b]).

langage([a | S]):- langage(S).

Upvotes: 0

Views: 46

Answers (1)

gusbro
gusbro

Reputation: 22585

You can think of a state machine that consumes its input. It has 2 states, one in which you can "eat" any amount of as and succeeds if it consumes all the input. If in that state you consume a b you go to the second state which only accepts any amount of as and again succeeds if it consumes all the input:

% state 1:
as_or_b([]).
as_or_b([a|L]):- as_or_b(L).
as_or_b([b|L]):- as(L).

% state 2:
as([]).
as([a|L]):- as(L).

Sample runs:

?- as_or_b([]).
true.

?- as_or_b([a]).
true.

?- as_or_b([b]).
true.

?- as_or_b([a,a,b,a,a]).
true.

?- as_or_b([a,a,b,a,a,b]).
false.

Upvotes: 1

Related Questions