非常基本的 dcg prolog 语法 [英] Very basic dcg prolog syntax
问题描述
我正在尝试理解序言和定语从句语法,但我很难理解它们.
I am trying to understand prolog and definite clause grammar but I am having a very hard time understanding both of them.
我真的很想了解如何使用 dcg 语法...
I am really trying to understand how to use the dcg syntax...
这里有两个例子:
第一个实际上是来自本论坛另一个问题的代码,但还有一个问题:
The first is actually the code from another question on this forum but with an additional question:
代码如下:
s --> first, operator, second.
first --> [X].
operator --> ['+'].
second --> [X].
当 Prolog 被问到这个时,它返回真/假,但我一生都无法弄清楚如何实际修改它以绑定"值,所以如果问 s(X, [2,+,2],[]).它会返回 first 的值,所以它不会返回 true 而是说 X = 2
And when Prolog is asked about this, it returns true/false but I can't for the life of me figure out how to actually modify this to "bind" the value so if asked s(X, [2,+,2],[]). it would return the value of first, so instead of returning true it'd say X = 2
无论如何回到实际问题.我在普通序言中有一些规则,这是其中之一;它实际上并没有做任何事情,只是作为示例而已.
Anyway back to the actual question. I have a few rules in normal prolog and this is one of them; it doesn't actually do anything and was merely made up as an example.
do(X, Y, [H|T], Sum):-
H == 1, %check if H is 1
X = H,
Y = T,
Additional is H+5,
Sum is Additional+Additional.
基本上,我是在问是否有人可以将其翻译成 DCG,以便我可以尝试理解 DCG 的基本语法!我试过阅读一些教程,但我觉得我没有变得更聪明......
Basically, I am asking if someone could translate this to DCG so that I could try and understand the basic syntax of DCG! I've tried reading some tutorials but I feel like I haven't gotten any wiser...
推荐答案
DCG:foo(A1, A2, A3, ... , An) --> bar.
DCG: foo(A1, A2, A3, ... , An) --> bar.
序言:foo(A1, A2, A3, ... , An, X, Y) :- bar(X,Y)
Prolog: foo(A1, A2, A3, ... , An, X, Y) :- bar(X,Y)
所以,s
应该改为:
s(X) --> first(X), operator, second.
first(X) --> [X].
operator --> ['+'].
second --> [X].
当然,返回实际结果可能更好;为此,您应该将 prolog 代码封装在 DCG 子句中,该子句使用 {}
完成:
Of course, it might be better to return the actual result; to do this you should encapsulate prolog code in the DCG clause which is done with {}
:
s(Z) --> first(X), operator, second(Y), {Z is X+Y}.
first(X) --> [X].
operator --> ['+'].
second(X) --> [X].
(当然,如果你有更多的操作符,prolog 代码不会那么简单).
(naturally, if you have more operators, the prolog code won't be that simple).
关于 do/4
谓词,它应该是这样的:
Regarding the do/4
predicate, it should be something like this:
do(X,Y,[H|T],Sum) -->
{H == 1, %check if H is 1
X = H,
Y = T,
Additional is H+5,
Sum is Additional+Additional}.
但我不明白你为什么想要那个.
but I don't see why you would want that.
最后一个提示:建议使用 phrase/3
而不是在 DCG 谓词中添加最后两个参数.
One last tip: it's recommended to use phrase/3
instead of adding the last two arguments in a DCG predicate.
这篇关于非常基本的 dcg prolog 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!