Definite Clause Grammar - Prolog

195 views Asked by At

Below I have a Definite Clause Grammar that should accept the string aabccc, however when I tested the grammar, the only string I was able to get accepted was abc.

I'm pretty sure I've gotten rid of left-hand recursion, so I'm not sure what's going wrong.

s --> x, y, z.
x --> [a], x.
x --> [a].
y --> [b], y.
y --> [b]. 
z --> [c], z.
z --> [c].

Also, would I be able to define the above grammar as...

s --> x, y, z.
x --> [a], x; [a].
y --> [b], y; [b].
z --> [c], z; [c].
1

There are 1 answers

1
Paulo Moura On BEST ANSWER

Both version of your grammar work as expected:

?- phrase(s, [a,a,b,b,c,c,c], R).
R = [] .

?- phrase(s, [a,a,b,b,c,c,c]).
true .

Maybe the issue was that you're trying to call it not with e.g. a [a,a,b,b,c,c,c] list of tokens but with a aabccc atom? If that's the case, you can use the standard atom_chars/2 built-in predicate to convert an atom into a list of characters:

?- atom_chars(aabccc, Tokens).
Tokens = [a, a, b, c, c, c].