I picked up prolog a couple of days ago and I 'm kind of stuck to this question. I want to subtract a number recursively until that number becomes less than 0. In pseudocode that would be like:
N:=0
while(Y>=X)
{
Y := Y-X
N := N+1
Y := Y+2
}
So for example if I have Y=20
and X=10
then we would get N=2
and Y=4
.
Any ideas? Thanks in advance. Any help appreciated. I'm using SWI Prolog.
EDIT 1 What I've accomplished so far is(although I'm not sure even if its correct):
sufficient(X, Y, M, N, F) :-
F is Y-X,
Y>=X,
plus(M, 1, N),
sufficient(X, F, N, N, F).
I have problem finding my base case, I'm confused on how to implement it. Also, in the sufficient
I have implemented, obviously when Y<X
it terminates returning false. Is there a way to get the N and F before terminating? I am feeling that I am not thinking the "prolog" way, since I am mostly used on C and that vagues my thinking. Thanks.
EDIT 2
I have found my base case and I can stop recursion however, I can't manage to ge the correct values. My code:
sufficient(X, Y, M, N, F) :- Y<X.
sufficient(X, Y, M, N, F) :-
F is Y-X,
plus(M, 1, N),
sufficient(X, F, N, D, E).
Thing is after the first recursion, if for example I call sufficient
as sufficient(10,21,0,N,F).
from the swi prolog command prompt, I 'll get N=1 and F=11. That happens because I make 2 new variables D and E. If I don't make those 2 new variables(D and E
), and at the 3rd sufficient
in the code I call N and F
instead of D and E
at the line F is Y-X
, I get a false
, because F
is 11 and Y-X
is 1. Do I have to set the a subtraction function myself, since F is Y-X
is not exactly a subtraction? Any ideas on how to do it?
nat_nat_sum/3
:nat_nat_dif(A, B, D) :- nat_nat_sum(B, D, A).
– falseis
is sufficient. – Topological Sort