什么是使用后继的减法和求和,任何人都可以向我展示一个我知道如何以正常方式进行的示例。
/* sub(X, Y, Z) ---减法 */
子(X,Y,Z):-添加(Y,Z,X)。
什么是使用后继的减法和求和,任何人都可以向我展示一个我知道如何以正常方式进行的示例。
/* sub(X, Y, Z) ---减法 */
子(X,Y,Z):-添加(Y,Z,X)。
首先,您需要有一个谓词succ。SWI-Prolog 是这样定义的:
succ(?Int1, ?Int2)
True if Int2 = Int1+ 1 and Int1>=0. At least one of the
arguments must be instantiated to a natural number. This predicate
raises the domain-error not_less_than_zero if called with a negative
integer. E.g. succ(X, 0) fails silently and succ(X, -1) raises a
domain-error.
鉴于此,我们可以add这样定义:
add(0, Y, Y).
add(X, Y, Z) :-
succ(PredX, X),
add(PredX, Y, PredZ),
succ(PredZ, Z).
像这样subtract:
subtract(X, 0, X).
subtract(X, Y, Z) :-
succ(PredY, Y),
succ(PredX, X),
subtract(PredX, PredY, Z).
请注意,这些都不会处理负数(因为succ没有),因此我没有费心在Y > X.
这是适用于任何实例化模式的addand的版本。subtract我仍然没有打扰类型检查(正如 Kaarel 在评论中提到的那样)或负数。
add(0, 0, 0).
add(0, Y, Y).
add(X, 0, X).
add(X, Y, Z) :-
nonvar(X),
succ(PredX, X),
(nonvar(Z) ->
succ(PredZ, Z), add(PredX, Y, PredZ)
;
add(PredX, Y, PredZ), succ(PredZ, Z)
).
add(X, Y, Z) :-
nonvar(Y),
add(Y, X, Z).
subtract(0, 0, 0).
subtract(X, 0, X).
subtract(X, X, 0).
subtract(X, Y, Z) :-
add(Y, Z, X).