简体   繁体   English

Prolog-递归除数

[英]Prolog - making a recursive divisor

Okay, so I'm a beginner in Prolog so I'm sorry if I can't quite get my question across very clearly but this is where I'm struggling: 好的,所以我是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.

I'm trying to write a program that will accept two arguments (X and D) and return the Iterations (I) and Remainder (R) so that it can display the result of X / D when the user enters: divide_by(8,3,I,R). 我正在尝试编写一个程序,该程序将接受两个参数(X和D)并返回Iterations(I)和Remainder(R),以便在用户输入时可以显示X / D的结果:dividly_by(8, 3,I,R)。 for example. 例如。

When tracing the code I know that I is incorrect because the first increment makes it equal to 0 and so the count for that is wrong. 跟踪代码时,我知道我是不正确的,因为第一个增量使它等于0,因此该计数是错误的。 But I don't know how to declare I is 0 without it resetting every time it recurses through the loop. 但是我不知道如何声明我为0,而不会在每次循环中都将其重置。 (I don't want to declare I as 0 in the query) (我不想在查询中将我声明为0)

I also realised that when it has finished recursing (when X < D) then I is going to be set to 0 because of the base case. 我还意识到,当完成递归操作时(当X <D时),由于基本情况,我将被设置为0。

Would anyone be kind enough to show me how I can fix this? 有谁愿意向我展示如何解决这个问题?

You need to introduce an accumulator and use a helper predicate, something like this: 您需要引入一个累加器并使用一个辅助谓词,如下所示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM