Download An Introductory Course on Constraint Logic Programming

Transcript
Chapter 5
Pragmatics
In this chapter we will briey discuss some programming tips and advanced features which
are treated more in depth in specialized literature on constraint logic programming. Our aim
is mainly to draw attention on their existence, because sometimes using them can make the
dierence among a complicated, sluggish system, and a clean, neat one.
5.1 Programming Tips
Control primitives should be used carefully, at least for a rst implementation: they can lead
to incorrect programs in CLP more easily than in Prolog. This is so because some implicit
assumptions on the classication of cuts for Prolog, which was based on the behavior of some
builtins, cannot be extended to CLP. The Prolog-safe code for max/3 in Section 4.7, translated
below to Prolog IV, is not safe any more:
max(X,Y,X):- gtlin(X, Y),!.
max(X,Y,Y):- lelin(X, Y).
The fact is that the comparison performed by gtlin/2 can now succeed on two free
variables, so on backtracking lelin/2 might be called as well|and this is disallowed by the
cut. The following call exhibits a wrong behavior:
?- max(5, X, Y), X = 8.
false.
since the correct answer would have been X = 8, Y = 8. The programmer has to ensure that
the proper instantiation mode is used when calling such predicates (which in fact breaks their
declarative transparency), or be aware that answers can be lost, depending on the constraint
system supported by the language.
)
One of the initial tasks in CLP is making up a correct model of the problem. When
coming to a neat model, people naturally try to be frugal in the use of relationships, and
not to set up too many equations. This is a sensible advice in general, but for some cases
putting redundant constraints is advantageous: the reason is that it shortens communication
paths inside the solver, so that faster reductions are possible. As an example, if we have
89