Search code examples
prologswi-prologconstraint-handling-rules

Constraint Handling Rules in SWI Prolog: The `neq` constraint doesn't work


I am learning Constraint Handling Rules (CHR) in swi-prolog.

I started with the tutorial from Tom Schrijvers' Constraint Handling Rules A Tutorial for (Prolog) Programmers.

In p.286, the author gave an example to implement Inequality constraint.

:- use_module(library(chr)).

:- chr_constraint neq/2.

neq(X,X) <=> fail.
neq(X,Y) <=> X \= Y | true.

But it does not work as expected in swi-prolog.

For example, in swi-prolog

?- neq(A,B).
true.

?- neq(A,B), A = B.
A = $VAR(B).

but it should be

?- neq(A,B).
neq(A,B).

?- neq(A,B), A = B.
false.

How can I get the same result as in the slide?

My swi-prolog version (threaded, 64 bits, version 8.2.4) on windows.

Thanks.


Solution

  • You may use ?=/2 for your second clause:

    :- use_module(library(chr)).
    :- chr_constraint neq/2.
    
    neq(X,X) <=> fail.
    neq(X,Y) <=> ?=(X,Y) | true.
    

    Sample runs:

    ?- neq(a,a).
    false.
    
    ?- neq(a,b).
    true.
    
    ?- neq(A,B).
    neq(A, B).
    
    ?- neq(A,B), A = f(C), B = f(D).
    A = f(C),
    B = f(D),
    neq(f(C), f(D)).
    
    ?- neq(A,B), A = [1,X], B=[].
    A = [1, X],
    B = [].