我正在做Ivan Bratko的《Prolog Programming for Artificial Intelligence》一书中的练习。练习要求如下:
定义操作符’if’、’then’、’else’和’:=’,使得以下表达式成为合法项:
if X > Y then Z := X else Z := Y
选择优先级,使’if’成为主要函子。
我在确定操作符’then’和’else’中哪个应该具有较低的优先级(并更强地绑定)时遇到了麻烦。我对这个问题的回答是:
:- op(900, fx, if).:- op(800, xfx, else).:- op(700, xfx, then).:- op(600, xfx, :=).
(书中也提到’>’操作符的优先级为700)。
我原本以为’then’的绑定强度会比’else’强,然而练习的答案却表明并非如此:
:- op(900, fx, if).:- op(800, xfx, then). :- op(700, xfx, else). :- op(600, xfx, :=).
我对’else’的优先级低于’then’的理由不太确定。任何见解都将不胜感激。
回答:
例如,考虑使用你的定义:
?- write_canonical(if a then b else c).if(else(then(a,b),c))true.
以及书中的定义:
?- write_canonical(if a then b else c).if(then(a,else(b,c)))true.
进一步,使用你的定义:
?- write_canonical(if a then (if b then c) else d).if(else(then(a,if(then(b,c))),d))true.
以及书中的定义:
?- write_canonical(if a then (if b then c) else d).if(then(a,else(if(then(b,c)),d)))true.
特别注意,使用你的定义,if ... then ... else
有时被解析为if(else(...
,有时被解析为if(then(...
!