无法在prolog中定义中缀二进制运算符

Bud*_*dyW 5 operators prolog swi-prolog

我刚刚开始讲道.我想定义一个中缀二进制运算符"rA",当我给出矩形的宽度和宽度时,它给出了矩形区域.这是我的代码:

:-op(300, xfy, rA).

rA(X,Y,R) :- R is X*Y.
Run Code Online (Sandbox Code Playgroud)

我执行此操作时代码工作正常:

1 ?- rA(3,4,A).
A = 12. 
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚的是将其定义为中缀二元运算符.我收到此错误:

2 ?- A is 3 rA 4.
ERROR: evaluable `3 rA 4' does not exist 
Run Code Online (Sandbox Code Playgroud)

谢谢

Pau*_*ura 8

你不能在标准的Prolog中做到这一点.但是,SWI-Prolog曾用于支持算术函数的用户定义,但我认为,在最近的版本中,该功能已被弃用.查看文档.一种可能的替代方案是利用几个Prolog系统(包括SWI-Prolog)定义的目标扩展机制和目标扩展is/2目标来处理利用用户定义的算术函数的调用.就像是:

goal_expansion(X is Expression, X is ExpandedExpression) :-
    % traverse and transform Expression
Run Code Online (Sandbox Code Playgroud)

但请记住,goal_expansion/2重复调用直到达到一个定点.因此,请注意尝试扩展已扩展的算术表达式所产生的无限循环.解决此问题的一种方法是使用在调用时检查的动态谓词来缓存扩展的结果goal_expansion/2.可以取消缓存动态谓词,例如,当您正在处理的文件结束时:

term_expansion(end_of_file, _) :-
    abolish(...), % the argument will be the predicate indicator of the caching predicate
    fail.
Run Code Online (Sandbox Code Playgroud)

end_of_file在执行任何必要的操作后,建议扩展失败,因为可能还有其他(正交)扩展也依赖于扩展end_of_file.