tags:

views:

25

answers:

2

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?

+2  A: 
s(N, M) --> [a], {N1 is N + 1}, s(N1, M), [b].
s(N, N) --> [].
s(N) --> s(0, N).

Usage:

?- phrase(s(N), [a,a,a,b,b,b]).
N = 3
Little Bobby Tables
+2  A: 
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.
thequark
That was exactly, what I wanted to have! :)
ubuntudroid