4

Let's say we have two variables X and Y. X is 53 and Y is 52. What I want to do is compare them by adding 1 to the Y, so that it would be 53 - therefore X would be equal to Y + 1.

I am trying to do it by simply using equal operator and addition for Y variables, like so:

X == Y + 1

Even though this looks simple enough, I am getting false as the result. What am I missing?

repeat
  • 18,496
  • 4
  • 54
  • 166
WheelPot
  • 307
  • 1
  • 3
  • 15

3 Answers3

2
?- X = 50+2, Y = 50+1, X =:= Y + 1.

as you can see, (=:=)/2 evaluates both sides, as do (>)/2, etc

CapelliC
  • 59,646
  • 5
  • 47
  • 90
1

If you are reasoning over integers, use your Prolog system's CLP(FD) constraints to compare and evaluate arithmetic integer expressions.

For example, in SICStus, SWI and YAP, after use_module(library(clpfd):

?- 53 #= 52 + 1. 
true.

This works in all directions.

Other examples:

?- X #= 52 + 1.
X = 53.

?- 53 #= Y + 1.
Y = 52.

?- 53 #= 52 + 1.
true.
mat
  • 40,498
  • 3
  • 51
  • 78
0

In order to evaluate expression trees, the is predicate is used:

X is Y+1.

you must be careful however, this will only work as a test if both X and Y are grounded. And will always error if variables on the right hand side (Y in this case) is not grounded.

swipl demo:

?- X = 53, Y = 52, X is Y+1.
X = 53,
Y = 52.

?- X = 53, Y = 52, X is Y.
false.
?- X = 53, X is Y+1.
ERROR: is/2: Arguments are not sufficiently instantiated
?- Y = 52, X is Y+1.
Y = 52,
X = 53.
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555