I'm trying to implement an increment in prolog, and have written the following code:
coordinate(X,Y,Z):-
X is 1,
Y is 1,
Z is 1,
coordinate(X1,Y1,Z1),
X1 is X+1,
Y1 is Y+1,
Z1 is Z.
I also tried:
coordinate(X,Y,Z):-
X is 1,
Y is 1,
Z is 1,
coordinate(X+1,Y+1,X+1).
Neither of these work. Can anyone explain why?
Neither program works because they contain infinite recursion. You call coordenate
within itself, without a stopping condition.
Then, to help you with your original problem of incrementing a variable in-place: you can't do that in Prolog. Once a variable is bound, you can't change its binding. When programming in Prolog, you have to think in terms of relations and recursion, not mutable state. Here's how to increment in Prolog:
incr(X, X1) :-
X1 is X+1.
Note that two variables are needed: one to hold the original value and one for the incremented value. To do anything useful with the computation that this predicate performs, both variables have to be arguments of the predicate. The first is meant as an input argument, the second as an output argument (though this isn't reflected in the language, it follows from the way is/2
works).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With