Search code examples
prolog

Prolog why the following term doesn't unify?


In prolog = is used for unification, as far as I understand if the two terms can be matched maybe with the help if variable instantiation, they are unified.

So why the following query fails

?- 2+2 = 4.

Although 2+2 yields into 4 which is the same number as the other term.


Solution

  • What others have answered is correct, but here's a little more detail.

    In Prolog, the term 2+2 is just a syntactical alternative to the term, '+'(2, 2). This is a term with functor + and with two arguments (2 and 2). The term 2 is just an interger and has no arguments. The =/2 operator attempts to unify terms. It does not perform arithmetic expression evaluation. These terms are clearly different and cannot be unified (they don't even have the same number of arguments).

    There are operators in Prolog which will perform the expression evaluation. For expression equality, you can use =:=/2 or better, as @mat points out for reasoning over integers, you can use #=/2. So the following will work:

    | ?- 2+2 =:= 4.
    
    yes
    | ?- 2+2 #= 4.
    
    yes
    | ?- 
    

    There is also is/2 which will evaluate the second argument only and determine if it's value is the same as the value of the first argument. Thus the following will happen:

    | ?- 2+2 is 4.
    
    no
    | ?- 4 is 2+2.
    
    yes
    | ?- 
    

    The above examples are in GNU prolog. Note that in SWI Prolog you must include the CLP(FD) library to use operators that reason over integers:

    :- use_module(library(clpfd)).