Prolog infix operator definition

旧时模样 提交于 2021-02-07 20:32:12

问题


I am recently learning about Prolog and I find the three types used for defining infix operators confusing.

What are the differences between xfx, xfy and yfx when specifying the type of an operator? I have googled about the problem and haven't found anything useful.

I tried typing the following codes in Prolog:

:- op(500,yfx,is_alive).
is_alive(A,B) :- display([A,B]).
:- op(500,xfy,is_alive2).
is_alive2(A,B) :- display([A,B]).
:- op(500,xfx,is_alive3).
is_alive3(A,B) :- display([A,B]).

and the output:

| ?- 1 is_alive 2.
'.'(1,'.'(2,[]))

yes
| ?- 1 is_alive2 2.
'.'(1,'.'(2,[]))

yes
| ?- 1 is_alive3 2.
'.'(1,'.'(2,[]))

yes

The results showed no difference to me.


回答1:


The 'type' of the operator controls associativity, e.g. whether expression "5 - 4 - 3" should be interpreted as "(5 - 4) - 3", which is known as left associativity or as "5 - (4 - 3)", which is right associativity.

If the minus operator should work as usually expected, is needs to be defined as 'yfx' which makes it left-associative. Other types as 'xfx and 'xfy' are variations on this. See more at http://www.cse.unsw.edu.au/~billw/cs9414/notes/prolog/op.html.




回答2:


If your Prolog is ISO compliant, you can use write_canonical to analyze the effect of operators precedence and associativity. For instance

?- write_canonical(1+2*3).
+(1,*(2,3))
true.


来源:https://stackoverflow.com/questions/9340792/prolog-infix-operator-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!