Question

I am trying to work out this simple DCG assignment (Prolog) for my course. The prblem is about creating a DCG. I have already defined a Universe of Discourse in my code. But this question is a bit misleading to me. According to what I've read and know, using my own notes and this Learn Prolog Now! - LINK: http://www.learnprolognow.org/lpnpage.php?pagetype=html&pageid=lpn-htmlse29

One can construct a DCG with (a^nb^nc^n). Where a b and c are normal letters and n is the number the letter is to be multiplied with. However, my question is like this.

"Design and implement a DCG to recognize (or generate) the language 0n1n0n."

Can somebody please help me out here? What is exactly wanted by the question?

With regards to one of the answers, I have tried the following code with no luck.

s --> [].
s(M) --> a(M),b(M),c(M).

a --> [].
a(New) --> [0], a(Cnt),{New is Cnt+1}.

b --> [].
b(New) --> [1], b(Cnt),{New is Cnt+1}.

c --> [].
c(New) --> [0], c(Cnt),{New is Cnt+1}.

count(T, N) --> [0,1,0], count(T, M), {N is M+1}.
count(_, 0) --> [].
Was it helpful?

Solution

DCGs are a sublanguage hosted in Prolog, then it's easy to count occurrences of a terminal T.

count(T, N) --> [T], count(T, M), {N is M+1}.
count(_, 0) --> [].

?- phrase(count(a, C), [a,a,a]).
C = 3 ;
false.

Of course, you should find this can solve your question easily.

EDIT: I missed the generation part. count//2 will not work for generation, because of builtin arithmetic. Using the successors notation the code can work as a generator too:

count(T, s(N)) --> [T], count(T, N).
count(_, 0) --> [].

OTHER TIPS

I think "0n1n0n" means "0n1n0n", i.e. some number of zeros, followed by same number of ones and followed by same number of zeros again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top