Search code examples
prologclpfd

Prolog Beginner: How to unify with arithmetic comparison operators or how to get a set var to range of values


I am new to Prolog. I need to write an integer adder that will add numbers between 0-9 to other numbers 0-9 and produce a solution 0-18. This is what I want to do:

% pseudo code
add(in1, in2, out) :-
    in1 < 10,
    in2 < 10,
    out < 18.

I would like to be able to call it like this:

To check if it is a valid addition:

?- add(1,2,3).
true.
?- add(1,2,4).
false.

With one missing variable:

?- add(X,2,3).
X = 1.
?- add(1,4,X).
X = 5.

With multiple missing variables:

?- add(X,Y,Z).
% Some output that would make sense.  Some examples could be:
X=1, Y=1, Z=2 ;
X=2, Y=1, Z=3 ......

I realize that this is probably a pretty simplistic question and it is probably very straightforward. However, according to the Prolog tutorial I am using:

"Unlike unification Arithmetic Comparison Operators operators cannot be used to give values to a variable. The can only be evaluated when every term on each side have been instantiated."


Solution

  • Solution:

    lessThanTen(9).
    lessThanTen(8).
    lessThanTen(7).
    lessThanTen(6).
    lessThanTen(5).
    lessThanTen(4).
    lessThanTen(3).
    lessThanTen(2).
    lessThanTen(1).
    lessThanTen(0).
    
    addSimple(Add1,Add2,Sol) :-
        lessThanTen(Add1),
        lessThanTen(Add2),
        Sol is Add1+Add2.