序言中的两个自然数 [英] Division two naturals in prolog
本文介绍了序言中的两个自然数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了以下代码:
nat(0).
nat(s(X)) :- nat(X).
divide(0,_,0).
divide(X,Y,D) :- X@<Y, D is 0.
divide(X,s(0),X).
divide(_,0,undefined) :- !.
一切都在这里.但是我应该写什么来计算另外两个自然数的除法呢?例如
Everything is right up to here. but what should i write, to calculate the division of two other naturals? for example
divide(s(s(s(s(s(s(s(s(0)))))))),s(s(0)),D).???
推荐答案
我认为最简单的方法是定义减法,然后通过计数器递归应用.我现在无法运行此程序,但我认为它看起来像这样:
I think the easiest way would be to define subtraction and then apply it recursively with a counter. I'm not able to run this right now but I assume it'd look something like this:
nat(0).
nat(s(X)) :- nat(X).
divide(_,0,_):- !, fail.
divide(X,Y,R):-
iter_subtract(X,Y,0,R).
iter_subtract(X,Y,N,N):- X@<Y, !.
iter_subtract(X,Y,C,R):-
subtract(X,Y,N),
D = s(C),
iter_subtract(N,Y,D,R).
subtract(A,0,A):-!.
subtract(s(X),s(B),R):-
subtract(X,B,R).
这篇关于序言中的两个自然数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文