Search code examples
prologgrammardcg

Counting definite clause grammar recursions in Prolog


I have the following Prolog definite clause grammar:

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

This will result in words like [a,a,b,b] being accepted in opposite to words like [a,b,a,b]. To put it in a nutshell the grammar is obviously a^n b^n. Now I want to return n to the user. How can I calculate n?


Solution

  • s(X)-->[a],s(Y),[b],{X is Y+1}.
    s(0)-->[].
    

    One needs to give parameters to the DCG non terminals. Please take care equality doesn't work exactly like assignment of imperative programming languages so X is Y + 1 was used.

    Some sample outputs:

    s(X,[a,b,b,b],[]).
    false.
    
    s(X,[a,a,a,b,b,b],[]).
    X = 3 ;
    false.