Addition function in Prolog

336 Views Asked by At

Is there a way I can create a function for addition/3 which does that:
add(1,2,X) - X is 3.
add(1,X,3) - X is 2.
add(X,2,3) - X is 1.

1

There are 1 best solutions below

0
On

As a beginner, the best is to use library(clpfd) which provides all that functionality ; and even more than that. With

?- use_module(library(clpfd)).

We start, in SICStus you have now to tell assert(clpfd:full_answer), then we have:

?- 1+2#=Z.
   Z = 3.
?- 1+Y#=3.
   Y = 2.

as you expected it. But even more than that!

?- X+X#=Z.
   2*X#=Z.
?- X+X#=X.
   X = 0.
?- X+Y#=Z.
   X+Y#=Z.