4

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!!!

false
  • 10,264
  • 13
  • 101
  • 209
pfc
  • 1,831
  • 4
  • 27
  • 50
  • 1
    Note that if `plus/3` is defined as a built-in (it is), then: `?- plus(1,X,2). X = 1.` –  Nov 09 '16 at 09:40

1 Answers1

2

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.

coder
  • 12,832
  • 5
  • 39
  • 53
  • Oh. It's perfect! Thank you so much! BTW, what is the library you mentioned used for? Why is this problem solved in this way? Thank you ! – pfc Nov 09 '16 at 07:11
  • 2
    Because as i mentioned you need something more relational than simple function. – coder Nov 09 '16 at 07:44