[英]Prolog - making a recursive divisor
好的,所以我是Prolog的初學者,所以很抱歉我不能很清楚地回答我的問題,但這就是我在努力的地方:
divide_by(X, D, I, R) :- (D > X), I is 0, R is X.
divide_by(X, D, I, R) :-
X >= D,
X_1 is X - D,
I_1 is I + 1,
divide_by(X_1, D, I_1, R),
R is X_1.
我正在嘗試編寫一個程序,該程序將接受兩個參數(X和D)並返回Iterations(I)和Remainder(R),以便在用戶輸入時可以顯示X / D的結果:dividly_by(8, 3,I,R)。 例如。
跟蹤代碼時,我知道我是不正確的,因為第一個增量使它等於0,因此該計數是錯誤的。 但是我不知道如何聲明我為0,而不會在每次循環中都將其重置。 (我不想在查詢中將我聲明為0)
我還意識到,當完成遞歸操作時(當X <D時),由於基本情況,我將被設置為0。
有誰願意向我展示如何解決這個問題?
您需要引入一個累加器並使用一個輔助謂詞,如下所示:
divide(_,0,_,_) :- !, fail . % X/0 is undefined and so can't be solved.
divide(0,_,0,0) :- !. % 0/X is always 0.
divide(X,Y,Q,R) :- % the ordinary case, simply invoke the
divrem(X,Y,0,Q,R) % helper with the accumulator seeded with 0
.
divrem(X,Y,Q,Q,X) :- % if X < Y, we're done.
X < Y . %
divrem(X,Y,T,Q,R) :- % otherwise...
X >= Y , % as long as X >= Y,
X1 is X - Y , % compute the next X
T1 is T + 1 , % increment the accumulator
divrem(X1,Y,T1,Q,R) % recurse down
. % Easy!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.