【发布时间】:2020-10-12 22:08:09
【问题描述】:
给定签名(0,Z,{plus(2),minus(2),times(2)},常量是整数,函数是加号、减号和时间,每个都有arity 2。我想编写两个谓词arth/2 和printarth/1,它们采用上述签名中的项并进行必要的算术计算加法、减法和乘法。arth/2 将打印结果,printarth/1 将得出评估表达式如下图。
我想实现两件事
第一:
?- arth( plus(minus(8,2), times(4,-3)), N).
N = -6
N is evaluated as ((8−2) + (4∗−3)) = (6 +−12) =−6
秒:
?- printarth(plus(minus(8,2), times(4,-3)), N).
((8 - 2) + (4 * -3))
true.
我了解Terms, Ops and complex terms 的使用用于此目的,我的代码如下所示
arithmetic_operator('+').
arithmetic_operator('-').
arithmetic_operator('*').
arithmetic_expression(N) :- integer(N).
arithmetic_expression(Term) :-
Term =..[Functor,Component1,Component2],
arithmetic_operator(Functor),
arithmetic_expression(Component1),
arithmetic_expression(Component2).
从这里我发现如何创建arth/2 和printarth/1 很困难,因为我无法调用arithmetic_expression(Term) 并在调用它时抛出错误。
?- arithmetic_expression(..[+,5,7]).
ERROR: Syntax error: Operator expected
ERROR: arithmetic_expression(.
ERROR: ** here **
ERROR: .[+,5,7]) .
有关此任务的任何资源都非常有用。
【问题讨论】:
-
明显的误解:有一个谓词叫
univ,定义为运算符,看起来像这样:=..。您已经在代码中使用它。=本身也是一个运算符(统一)。但是..本身什么都不是。
标签: prolog signature predicate first-order-logic