为给定的上下文无关语法生成符号字符串(句子)
我有一个简单的语法,例如
S::=a S b
S::=[] (empty string)
现在我想为上述语法编写一个解析器,例如
cfg('S', [a,'S',b])
通过最左推导生成一个句子 aaabbb 。
我不足以处理序言中的 dcg/cfg 。 所以请帮助我解决这个例子,以便我可以继续尝试更大的事情。
I have a simple grammar such as
S::=a S b
S::=[] (empty string)
Now i want to write a parser for the above grammar like
cfg('S', [a,'S',b])
which generates a sentence aaabbb by left most derivation.
I'm not good enough to handle dcg/cfg in prolog.
So pls help me with this example so that i can go ahead and try something bigger.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
考虑这个 DCG 代码:
要运行由 DCG 定义的谓词,您应该在末尾添加两个参数:“输入”及其剩余内容。如果您想识别整个列表,只需输入 []。因此,当您运行它时,您会得到:
如果您想要某种“返回”字符串,您可以将其添加为额外的参数。要在 dcg 子句中编写 prolog 代码,您可以使用 {}:
,您会得到:
我们生成了此语法可识别的所有字符串;通常你只想检查语法是否可以识别字符串。为此,您只需将其作为输入:
请注意,我们将 S::=[] 规则放在第一位,否则如果您要求生成所有解决方案,序言将陷入无限循环。在更复杂的语法中解决这个问题可能并不容易。要获得解决方案,您可以使用 length/2:
即使您的代码是:
Consider this DCG code:
to run a predicate you defined by DCG you should add two more arguments at the end: the "input" and what it's left. If you want to recognize the whole list you simply put []. So, when you run it you get:
If you wanted some sort of "return" string you could add it as an extra arg. To write prolog code in a dcg clause you use {}:
and you get:
we generated all the strings that are recognized by this grammar; usually you just want to check if a string is recognized by the grammar. to do that you simply put it as input:
note that we put the S::=[] rule first otherwise prolog would fall in a infinite loop if you asked to generate all the solutions. This problem might not be trivial to solve in more complex grammars. To get the solutions you can use length/2:
even if your code is: