Prolog 运算符优先级和规则匹配
我在序言解释器中加载了接下来的两个事实:
foo(U+V,1).
foo(U*V,2).
现在我尝试使用该结果进行下一个查询:
foo(x*x+x,R). --> R = 1
foo(x+x*x,R). --> R = 1
foo(x*x*x,R). --> R = 2
现在我尝试使用下一个查询:
foo(x*x-x,R). --> no
据我了解,这是通过运算符优先级如何构建树表达式来解释的:
x+x*x --> + so it matches with --> +
/ \ / \
x * U V
/ \
x x
x-x*x --> - DOES NOT matches any fact.
/ \
x *
/ \
x x
这是解释吗正确的?
I have the next two facts loaded in my prolog interpreter:
foo(U+V,1).
foo(U*V,2).
Now I try the next queries with that results:
foo(x*x+x,R). --> R = 1
foo(x+x*x,R). --> R = 1
foo(x*x*x,R). --> R = 2
Now I try with the next query:
foo(x*x-x,R). --> no
As I understand, this is explained by how the operator precedence build the tree expression:
x+x*x --> + so it matches with --> +
/ \ / \
x * U V
/ \
x x
x-x*x --> - DOES NOT matches any fact.
/ \
x *
/ \
x x
Is this explanation correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这是正确的。
默认运算符优先级被定义为自然的,即使用正常的数学优先级。 但如果你不喜欢这样,你可以重新定义它。
改变优先级是否是一个好主意是另一回事,它有效地改变了 Prolog 的语法并可能导致解析问题。 特别是如果您更改 Prolog 语法的运算符优先级(优先级高于 1000)。
Yes, this is correct.
The default operator precedence is defined to be natural, i.e. use the normal mathematical precedence. But if you don't like that you can redefine it.
Whether changing the precedence is a great idea is another matter, it effectively changes the syntax of Prolog and can lead to parsing problems. Especially if you change the precedence of the operators for the Prolog syntax, with precedence above 1000.