I am doing an exercise from ‘Prolog Programming for Artificial Intelligence’ by Ivan Bratko. The exercise says:
Define the operators ‘if’, ‘then’, ‘else’ and ‘:=’, so that the
following becomes a legal term:if X > Y then Z := X else Z := Y
Choose the precedences so that ‘if’ will be the principal functor.
I am having trouble determining out of the operators ‘then’ and ‘else’, which one should have the lower precedence (and bind stronger). My answer to this question was:
:- op(900, fx, if).
:- op(800, xfx, else).
:- op(700, xfx, then).
:- op(600, xfx, :=).
(It is also stated in the book that the ‘>’ operator has a precedence of 700).
I thought that ‘then’ would bind stronger than ‘else’, however the answer for this exercise states otherwise:
:- op(900, fx, if).
:- op(800, xfx, then).
:- op(700, xfx, else).
:- op(600, xfx, :=).
I am not sure of the rationale behind making ‘else’ have a lower precedence than ‘then’. Any insights are greatly appreciated.
2
Answers
Consider for example, with your definition:
and with the definition from the book:
and further, with your definition:
and with the definition from the book:
Note in particular that with your definition,
if ... then ... else
, is sometimes parsed asif(else(...
, and sometimes asif(then(...
!/*
When working on the creation of constructs requiring operators I like to start with
setting all of the operator priority’s to 10’1 .
If the construct can be made to work with all of the operators at priority at 10’1 that is ideal .
Once that is established then the priority can be changed to accomodate further requirements .
For example the further requirements of
if _if_ then _then_ else _else_
are considerations of what should be containable in the
_if_
and the_then_
and the_else_
parts .For example if that is desirable for
;
such asif foo ; bar then baz ; qux
then the priority will have to be greater than
10'1100
.For example if that is desirable for
,
such asif foo , bar then baz , qux
then the priority will have to be greater than
10'1000
.For example if that is desirable for
+
such asif + foo then + bar
then the priority will have to be greater than
10'950
.For example if that is desirable for
=
such asif _foo_ = bar then _baz_ = qux
then the priority will have to be greater than
10'700
.Those 4 operators are the most important considerations .
*/