序言中的除法
我试图使用余数定理和良序原则来定义序言中的除法。
到目前为止我已经得到:
less(0, s(0)).
less(0, s(B)) :- less(0, B).
less(s(A), s(s(B))) :- less(A, s(B)).
add(A,0,A) :- nat(A).
add(A,s(B),s(C)) :- add(A,B,C). % add(A,B+1,C+1) = add(A,B,C)
add2(A,0,A).
add2(A,s(B),s(C)) :- add2(A,B,C). % add(A,B+1,C+1) = add(A,B,C)
times(A,0,0).
times(A,s(B),X) :- times(A,B,X1),
add(A,X1,X).
eq(0,0).
eq(s(A), s(B)) :- eq(A, B).
% A / B = Q (R) => A = B * Q + R
div(A, B, Q, R) :- less(R, B), eq(A, add(times(Q, R), R)).
但是 div
的定义在某种程度上是错误的。有人可以给我提示吗?
PS:我不应该使用 eq
,但我无法让 is
或 =
工作。
I'm trying to define the division in prolog using the remainder theorem and the well-ordering principle.
I've got thus far:
less(0, s(0)).
less(0, s(B)) :- less(0, B).
less(s(A), s(s(B))) :- less(A, s(B)).
add(A,0,A) :- nat(A).
add(A,s(B),s(C)) :- add(A,B,C). % add(A,B+1,C+1) = add(A,B,C)
add2(A,0,A).
add2(A,s(B),s(C)) :- add2(A,B,C). % add(A,B+1,C+1) = add(A,B,C)
times(A,0,0).
times(A,s(B),X) :- times(A,B,X1),
add(A,X1,X).
eq(0,0).
eq(s(A), s(B)) :- eq(A, B).
% A / B = Q (R) => A = B * Q + R
div(A, B, Q, R) :- less(R, B), eq(A, add(times(Q, R), R)).
But the definition of div
is somehow wrong. Could someone please give me a hint?
PS: I shouldn't be using eq
, but I couldn't get is
or =
to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 SWI-Prolog 中,您可以尝试
?- gtrace, your_goal.
使用图形跟踪器并查看出了什么问题。您应该编写以下示例,而不是eq(A, add(times(Q, R), R))
:times(Q, R, T), add(T, R, A)
,因为您想要使用“times/3”和“add/3”谓词,而不是仅仅使用由“add/2”和“组成的复合术语调用“eq/2”谓词times/2" 作为第二个参数。代码还存在其他问题,例如缺少 nat/1 的定义,但我希望这会有所帮助。In SWI-Prolog, you can try
?- gtrace, your_goal.
to use the graphical tracer and see what goes wrong. Instead ofeq(A, add(times(Q, R), R))
, you should write for example:times(Q, R, T), add(T, R, A)
, since you want to use the "times/3" and "add/3" predicates, instead of just calling the "eq/2" predicate with a compound term consisting of "add/2" and "times/2" as its second argument. There are other problems with the code as well, for example, the definition of nat/1 is missing, but I hope this helps somewhat.