简体   繁体   中英

Problems with DCG (Prolog)

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 ab 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) --> [].

我认为“ 0n1n0n”的意思是“ 0 n 1 n 0 n ”,即一定数量的零,其次是相同数量的1,然后又是相同数量的0。

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) --> [].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM