user3365834
user3365834

Reputation:

swi-prolog strange recursion write

I have a similar recursion function:

fillTable(X0,Y0,Yn,Yh):-
   checkPoint(X0,Y0),
   Ynext = Y0+Yh,
   Ynext=<Yn,
   fillTable(X0,Ynext,Yn,Yh).

checkPoint(X,Y):-
     (-X-1)<Y,
     X<0, Y<0,
     write(X), writeq(' '), write(Y),write(' in 1 area'),
     nl,
     !
  ;
     (-X+1)>Y, X>0, Y>0,
     write(X),write(' '), write(Y),write(' in 2 area'),
     nl,
     !
  ;
     write(X),write(' '),write(Y),write(' not in area'),nl.

Where X, Y and other var's are float, but when it's written by write(), it prints -1+0.2+0.2+0.2+... not -0.8, -0.6 or other.

How can I fix it?

Upvotes: 1

Views: 80

Answers (1)

lurker
lurker

Reputation: 58324

This is a common beginner's issue in Prolog to confuse "unification" with "assignment".

Your expression:

Ynext = Y0+Yh,

Does not assign the value of Y0+Yh to the variable Ynext. The predicate =/2 is the unification predicate, which will take the expressions on both sides and unify them. These expressions are Ynext, a variable, and Y0+Yh, which is the functor +/2 applied to two other variables (which in your case, are instantiated). In other words, it unifies Ynext with +(Y0,Yh) and does not evaluate it.

Let's suppose then you have Y0 instantiated as -1 and Yh as 0.2. Then, the unification expression above will be:

Ynext = -1+0.2,

Which will result in Ynext having the value -1+0.2 (which is, in prolog, the same as +(-1,0.2).

If you want to evaluate the arithmetic expression and assign it, you'd use is/2:

Ynext is Y0 + Yh,

Note that the inequalities </2, >/2, etc do evaluate. So the expression:

(-X+1)>Y

Will do what you expect it to, which is to succeed or fail depending upon whether the value of the arithmetic expression (-X+1) is less than the value of Y or not.

Upvotes: 2

Related Questions