Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top