I'm new to Prolog. I wrote a very short program as follows:
plus(X,Y,R):- R is X+Y.
When I run it, I get the following problem:
?- plus(1,1,2).
true
?- plus(1,1,X).
X=2
?- plus(1,X,2).
ERROR: is/2: Arguments are not sufficiently instantiated
Why does the error happens? How can I modify the code to achieve the same goal? Thank you all for helping me!!!
The reason that this is not working is that is/2 is (like) a function. Given X,Y it calculates X+Y and stores it to R (it instantiates R with X+Y). If R is provided and X or Y is a var (it is not yet instantiated) then how could it calculate X+Y, that's why the instantiation error.
To solve this you should use something more relational like module :CLPFD
:- use_module(library(clpfd)).
plus(X,Y,R):- R #= X+Y.
Some examples:
**?- [ask].
true.
?- plus(1,1,2).
true.
?- plus(1,1,X).
X = 2.
?- plus(1,X,2).
X = 1.
?- plus(X,Y,2).
X+Y#=2.
?- plus(X,Y,R).
X+Y#=R.**
You can see in the last case that is gives as an answer how X,Y and R are related.