Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 views
in Technique[技术] by (71.8m points)

parsing - Is there a way or an algorithm to convert DCG into normal definite clauses in Prolog?

I am a newbie in Prolog, and I am trying to understand how a grammar can be translated into a normal definite clause from a DCG. I understood that DCG notation is just syntactic sugar for normal definite clauses in Prolog. I started to depict some similarities between the normal definite grammars, and the DCGs, but failed to apply the same pattern, so I am asking is there some rules that I am missing or an algorithm of conversion that might work.

Here is the grammar that I am working on, and here is what I did in order to translate that grammar:

expr --> term, addterm.
addterm --> [].
addterm --> [+], expr.
term --> factor, multfactor.
multfactor --> [].
multfactor --> [*], term.
factor --> [I], {integer(I)}.
factor --> ['('], expr, [')'].

This grammar actually checks the syntactic correctness of arithmetic operations. The first rule is actually easy to convert as its pattern is similar to normal definite grammars, and so is the 4th one. However I have no clue about the other four. Here is How I converted the rule:

expr(E0,E) :- term(E0,E1), addterm(E1,E).
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your Prolog system provides an expand_term/2 built-in predicate, you can use usually to expand grammar rules into clauses. For example:

?- expand_term((a --> b, c), Clause).
Clause = (a(_G1012, _G1013):-b(_G1012, _G1028), c(_G1028, _G1013)).

For a bit more readable output (and for this purpose only), try:

?- expand_term((a --> b, c), Clause), numbervars(Clause, 0, _).
Clause = (a(A, B):-b(A, C), c(C, B)).

numbervars/3 is a de facto standard predicate found on most Prolog systems.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...