-2

Using Prolog I'm trying to write a predicate that recognizes context free grammar and returns true if the input list matches the CFG.
The alphabet of the input consists only of a,b. The CFG i'm trying to match is

S-> TT
T -> aTb | ab

I'm not quite sure how to implement this, mainly the T rule.

s(S0,S):-t(S0,S),t(S1,S).
t(S0,S):-S0 = a, t(S1,S), S1 = b; S0 = a, S1 = b.

match([H|T] :- s(H,T).

So if I query [a, a, b, b] it should return true. However, I'm just getting an infinite loop. I'm not quite sure how to implement the a^n b^n rule.

false
  • 10,264
  • 13
  • 101
  • 209
Jay
  • 15
  • 1
  • 7
  • 4
    Possible duplicate of [Recognize A^n B^n language in Prolog with no arithmetics](http://stackoverflow.com/questions/16416153/recognize-an-bn-language-in-prolog-with-no-arithmetics), which can easily be specialized to handle this; the gist of it is, "use DCGs". – Fred Foo May 08 '13 at 10:27
  • This question was asked yesterday. Please spend thirty seconds searching for an answer that may already exist before asking. – Daniel Lyons May 08 '13 at 14:18

1 Answers1

3

I would write the CFG in this way:

S -> T
T -> a T b | {epsilon}

that translates directly to a DCG:

s --> t.
t --> [].
t --> a, t, b.

Note I swapped the epsilon rule, to get the ability to generate phrases.

Translating that DCG by hand :

s(S0,S) :- t(S0,S).
t(S0,S0).
t(S0,S) :- S0=[a|S1], t(S1,S2), S2=[b|S].

Yields

?- phrase(s,L).
L = [] ;
L = [a, b] ;
L = [a, a, b, b] ;
L = [a, a, a, b, b, b] ;
...
CapelliC
  • 59,646
  • 5
  • 47
  • 90