Session 10: Constraint Logic Programming

So far we have been using SWI prolog. However, SWI cannot handle (some kinds of) constraints, we will use SICStus prolog for this.

Constraint Logic Programming with Reals

We need to tell SICStus to load its special CLP(R) library:
?- use_module(library(clpr)). Now try the following two exercises:

Finite Domain Constraint Logic Programming

Often the variables don't range over all real numbers, but over a finite set of elements. SICStus supports finite sets of integers as finite domains. With in/2 or domain/3 we can specify this domain, we can impose constraints with #>/2 #=/2 etc. More constraint expressing predicates can be found in Bratko, p.341-345. To use CLP on a finite domain, first load the necessary libraries (warning: these may interfere with the other clp-libraries, first restart your prolog engine to avoid problems):
:- use_module(library(clpfd)).
Before we start with the actual exercises, note that the predicate exactly/3 is often very handy when solving CLP-problems. This predicate was discussed in the lectures, it checks (using CLP) whether an integer occurs in a list of integers exactly N times.
exactly(_El, [], 0).
exactly(El, [H|List], N) :-
    El #= H #<=> B,
    N #= M+B,
    exactly(El, List, M).

Now try to solve the following exercises: