我有这个非常简单的代码作为数字的表示。 问题是当我使用add2函数时。
示例: add2(s(0)+s(s(0)), s(s(0)), Z). 正确地返回s(s(s(s(s(0))))) 。 但是add2(0, s(0)+s(s(0)), Z). 总是returns s(0)+s(s(0)) 。 有人能看出为什么会这样吗?
numeral(0). numeral(s(X)) :- numeral(X). numeral(X+Y) :- numeral(X), numeral(Y). add(0,X,X). add(s(X),Y,s(Z)) :- add(X,Y,Z). %% exercise 1 add2(X,Y,R) :- add(X,Y,R). add2(X+Y,Z,R) :- add(X,Y,A),add2(A,Z,R). add2(X,Y+Z,R) :- add(Y,Z,A),add2(X,A,R).I have this very simple code as a representation of numerals. The problem is when I use the add2 function.
Example: add2(s(0)+s(s(0)), s(s(0)), Z). returns s(s(s(s(s(0))))) correctly. However add2(0, s(0)+s(s(0)), Z). always returns s(0)+s(s(0)). Can anyone see why this is happening?
numeral(0). numeral(s(X)) :- numeral(X). numeral(X+Y) :- numeral(X), numeral(Y). add(0,X,X). add(s(X),Y,s(Z)) :- add(X,Y,Z). %% exercise 1 add2(X,Y,R) :- add(X,Y,R). add2(X+Y,Z,R) :- add(X,Y,A),add2(A,Z,R). add2(X,Y+Z,R) :- add(Y,Z,A),add2(X,A,R).最满意答案
这是因为第一个add2子句和第一个add子句的组合。 你的add2(0, ..., ...)将触发add(0, ..., ...) ,它总是统一第二个和第三个参数。
It's happening because of the combination of the first add2 clause and the first add clause. Your add2(0, ..., ...) will trigger add(0, ..., ...) which always unifies the second and third argument.
更多推荐
发布评论