Next: , Previous: , Up: lib-chr   [Contents][Index]


10.8.5 Examples

Here are two example constraint solvers written in CHR.

  1. The program below defines a solver with one constraint, leq/2, which is a less-than-or-equal constraint, also known as a partial order constraint.
    :- module(leq,[leq/2]).
    :- use_module(library(chr)).
    
    :- chr_constraint leq/2.
    reflexivity  @ leq(X,X) <=> true.
    antisymmetry @ leq(X,Y), leq(Y,X) <=> X = Y.
    idempotence  @ leq(X,Y) \ leq(X,Y) <=> true.
    transitivity @ leq(X,Y), leq(Y,Z) ==> leq(X,Z).
    

    When the above program is loaded, you can call the leq/2 constraint in a query, e.g.:

    | ?- leq(X,Y), leq(Y,Z).
    leq(X,Y),
    leq(X,Z),
    leq(Y,Z) ?
    
  2. The program below implements a simple finite domain constraint solver.
    :- module(dom,[dom/2]).
    :- use_module(library(chr)).
    :- use_module(library(sets), [intersection/3]).
    
    :- chr_constraint dom(?int,+list(int)). 
    :- chr_type list(T) ---> [] ; [T|list(T)].
    
    dom(X,[]) <=> fail.
    dom(X,[Y]) <=> X = Y.
    dom(X,L) <=> nonvar(X) | memberchk(X,L).
    dom(X,L1), dom(X,L2) <=> intersection(L1,L2,L3), dom(X,L3).
    

    When the above program is loaded, you can call the dom/2 constraint in a query, e.g.:

    | ?- dom(A,[1,2,3]), dom(A,[3,4,5]).
    A = 3
    

Finally, Martin Keser’s WebCHR package at http://chr.informatik.uni-ulm.de/~webchr/ contains more than 40 example programs for SICStus 4, complete with documentation and example queries.


Send feedback on this subject.