Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing numbers in Prolog

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?

like image 319
Bernardo Ortiz Avatar asked Nov 21 '11 18:11

Bernardo Ortiz


1 Answers

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).

like image 198
Fred Foo Avatar answered Nov 08 '22 05:11

Fred Foo