25 November 2005 Foundations of Logic and Constraint Programming 1
Constraint (Logic) Programming
Anoverview
• BooleanConstraints
• CompleteSolversforSAT
• BooleanUnification
• CompleteSolversforLinearConstraints
• Applications
[Dech04]RinaDechter,ConstraintProcessing,
25 November 2005 Foundations of Logic and Constraint Programming 2
Boolean Constraints
Booleandomains(oftenreferredtoas0/1variables)hasmanyapplications,namely
InDigitalCircuits
o Exemple:Half-adder
Inproblemsmodellingbinarychoices
o Exemple:N-Queens
Inproblemsdealingwithsets
B
G1
G2
AC
S
25 November 2005 Foundations of Logic and Constraint Programming 3
Approaches to Boolean Constraint Solving
The satisfaction of Boolean constraints may be addresses in various and alternativeways
Simbolically• BooleanUnification• CompleteSolver
• SAT• AllconstraintsareconvertedintoClauses(CNF)• Solutionconstruction(backtracking)orrepairing(localsearch)
• Finite Domains• BooleansarejustaninstanceofaFinitedomain(0/1)• TechniquescommontootherFiniteDomains
25 November 2005 Foundations of Logic and Constraint Programming 4
Boolean Constraints
To handle Boolean satisfaction simbolically, it is convenient to convert all
BooleanconstraintsusingexclusivelyequalityconstraintonBooleanFormulas.
BooleanFormulasarecomposedof
TwoBooleanoperators
#(exclusiveor)and·(conjunction),
Booleanconstants
0e1(andpossiblyotherconstants,domaindependent)
variábles
denotedbyuppercaseletters
Thisconversionisalwayspossible,sincetheset{0, 1, #, ·}iscomplete.
Givenarbitrarytermsaandb,all theusualoperatorsandconstantsmaybe
expressedusingexclusivelythe“#”and“·”operators.
a = 1 # a ; a b = a · b ; a b= a # b # a · b
a b = 1 # a # a · b ; a b = 1 # a # b
25 November 2005 Foundations of Logic and Constraint Programming 5
Boolean Rings
More formally, the tuple< A, 0, 1, #, · >, where A any domain that
includestwoelements0and1,isabooleanring,ifthefollowingpropertiesare
satisfied
Associativity
a#(b#c) = (a#b)#c a·(b·c) = (a·b)·c Comutativity
a # b = b # a a · b = b · a Distribution
a #(b·c) = (a#b)·(a#c) a·(b#c) = a·b#a·c NeutralElement
a#0 = a a·1 = a ExclusivityandIdempotence
a#a = 0 a·a = a AbsorbingElement
a·0 = 0
25 November 2005 Foundations of Logic and Constraint Programming 6
Boolean Constraints on Sets
AlthoughBooleanconstraintsareusuallyconsideredondomainswithonlytwo
elements,anotherinterestingdomainofapplicationisSets.
Moreprecisely,consideringadomainPofallallsetscomposedofelements
a1,a2,a3,...,an
Constant1correspondstotheUniversalset{a1,a2,a3,...,an} Constant1correspondstotheEmptyset{} Operator“#”correspondstotheSetExclusiveUnion Operator“·” correspondstoSetIntersection
Other constraintsonsetsmaybeconverted intoequality.Forexample,given
theequivalence
a b a b = a a b = b
theincludesconstraint““canberewrittenas
a # b # a·b = b a # b # b # a·b = b # b
a # a·b = 0 a·b = a
25 November 2005 Foundations of Logic and Constraint Programming 7
Constraint Solving through Boolean Unification
The implementation of a symbolical and complete constraint solver fo
Booleans is the core of CLP(B), the instance of the CLP(X) scheme to the
BooleanDomain.
In this solver,Booleanconstraintsaremaintained ina solved form,obtained
throughBooleanunification.
ABooleanconstraintt1 = t2 (where termst1 et2 areexclusivelywritten
has the formwithoperators “#” and “·” .Such constraint canbe satisfied iff
thereisaBooleanUnifierfortermst1andt2.
ABooleanunifierisasetofpairsx / twherexandtarerespectivelyBoolean
variablesandterms(muchinthesamewayofunifiersinlogicprogramming),
andwherenoneofthevariablesmayappearintheterms.
As in logic programming, Boolean unifiers will be denoted by greek letters.
25 November 2005 Foundations of Logic and Constraint Programming 8
Boolean Unification: Examples
Example 1:Termst1=1 # A and t2 = A·BadmitthefollowingBooleanunifier
= {A/1, B/0}
Infact,denotingbyt(ort)theapplicationofsubstitution to term t,
t1 = (1#A){A/1, B/0}= 1 # 1 = 0
t2 = (A·B){A/1, B/0}= 1 · 0 = 0
whichguaranteesthatconstraintt1 = t2issatisfiable.
Example 2:Termst1 = 1 # A·Bandt2= C # Dadmitunifiers
= {C/1#A·B#D} and ={C/1#D, A/0}
since
t1 = (1#A·B) {C/1#A·B#D} = 1#A·B
t2 = (C#D) {C/1#A·B#D} = 1#A·B#D#D = 1#A·B
and
t1 = (1#A·B) {C/1#D, A/0} = 1#0·B = 1
t2 = (C#D) {C/1#D, A/0} = (1#D#D) = 1
25 November 2005 Foundations of Logic and Constraint Programming 9
Multiple Boolean Unifiers
Like in LP it is convenient to consider a hierarchy of unifiers, related by the
“moregeneral”relationship.
Unifierismore generalthen
thereisasubstitutionsuchthat
Example:Asseenabove,termst1 = 1 # A·Bandt2= C # D,admitunifiers
= {C/1#A·B#D} and ={C/1#D, A/0}
Inthiscase,ismoregeneralthan,sincefor{A/0}, itis.
= {C/1#A·B#D } o {A / 0} = {C/1#D, A/0} =
25 November 2005 Foundations of Logic and Constraint Programming 10
Most General Boolean Unifiers
Ingeneral,giventwoBooleanterms,t1et2,theremightbenotonlymorethan
oneunifiers,butalsomorethanonemostgeneralunifier.
Example: Booleantermst1 = 1 # A·Bandt2= C # Dmaybeunifiedbythe
mostgeneralunifiers
1 = { C / 1 # A·B # D}
2 = { D / 1 # A·B # C}
3 = { A / 1 # C # D, B / 1}
4 = { A / 1, B / 1 # C # D}
Noneof theunifiersmaybeobtainedby thecompositionofanyof theothers
andasubstitution.
25 November 2005 Foundations of Logic and Constraint Programming 11
Boolean Unification Algorithm
Taking into account that constraint t1 = t2 is equivalent to t1#t2= 0, the
unification of terms t1 and t2 is equivalent to constrain term t1#t2 to 0. The
conditionsnecessarytozeroatermt,maybeanalysedfollows:
1. Zeroingaconstanttermistriviallycheckable
a. Ift = 0thetermisalreadyzero;
b. Ift = 1termcannotbezeroed
• Given distribution, a non constant term t, can always be written in the form
a·U#b(whereUisoneofthevariablesoccurringint)factoringtinordertoU.
• A term t = a·U # b may onlty be zeroed if either a = 1 or b = 0, or both.
Otherwise, i.e.a = 0andb = 1, itwouldbe t = 1 0,whatever thevalue
chosenforU.
4. Suchcondition(a = 1or b = 0) isguaranteedifftheterm(1 # a)·b is
zeroed.
25 November 2005 Foundations of Logic and Constraint Programming 12
Boolean Unification Algorithm
5. Onceconditiona = 1or b = 0isguaranteed,
5. ifa = 0 (andb = 0), then variableU may take an arbitraru value,since0 = 0·U # 0)
6. ifa = 1,thenvariableUmusttakevalurb(inthiscase,0 = 1·U # b)
6. The assignment to U of these terms can be implemented by means of a
fresh variable, not occurring in t. Denoting by _U this new variable, the
previousconditionisequivalentto
U = (1#a)·_U # b
I. Infact,
I. Ifa = 0(andb = 0)thenU = _U,i.e.Umaytakeanyarbitraryvalue,sincevariable_U,beingafreshvariable,isnotconstrainedanywhere.
II. Ifa = 1thenU = (1#1)·_U # b,i.e.U = b,asintendend.
25 November 2005 Foundations of Logic and Constraint Programming 13
Boolean Unification Procedure
• The reasoning above can be used in the implementation of predicate
unif_bool,shownbelow.
predicate unif_bool(in: t1, t2; out: );
t t1 # t2;
unif_bool zero(t,);end predicate.
• Thepredicateinputstermst1andt2,thataretobeunified,andsucceedsif
predicatezero succeedes,returningunifierobtainedfromthispredicate.
25 November 2005 Foundations of Logic and Constraint Programming 14
Boolean Unification Procedure
Predicatezerocannowbeimplementedasshpownbelow
predicate zero (in: t; out: );case t = 0: zero = True, = {};case t = 1: zero = False;
otherwise:
A·u # B t; s (1#A)·B;
if zero(s,σ) then
zero True; {U/(1#A)·_U#B} o σ
else
zero = False
end if
end caseend predicate
25 November 2005 Foundations of Logic and Constraint Programming 15
Boolean Unification Procedure: Example
{U/(1#A)·_U#B} o σ
Noticethatsubstitutionreturnedbypredicatezero isobtainedthroughthe
composition of substitutions {U/(1#A)·U#B} and σ obtained from the
recursivecallofthepredicate.
Example:SatisfyconstraintX # X·Z = Y·Z # 1
Unify X#X·Z and Y·Z#1
zero X#X·Z#Y·Z#1
= (1#Z)·X#Y·Z#1 % Ax·X#Bx
zero (1#(1#Z))·(Y·Z#1) % (1#Ax)·Bx
= Z·(Y·Z#1)
= Z·Y#Z % Ay·Y#By
zero (1#Z)·Z %(1#Ay)·By
= 0
25 November 2005 Foundations of Logic and Constraint Programming 16
Boolean Unification Algorithm: Example
Nowletusanalysetheunifierthatisreturnedbythesequenceofcalls
Unify X#X·Z and Y·Z#1
zero X#X·Z#Y·Z#1 = (1#Z)·X#Y·Z#1
zero (1#(1#Z))·(Y·Z#1)=Z·Y#Z %(1#Ax)·Bx
zero (1#Z)·Z = 0 %(1#Ay)·By
σz = {}
σy = {Y/(1#Ay)·_Y#By} o σz
= {Y/(1#Z) ·_Y#Z} o {}
= {Y/(1#Z) ·_Y#Z}
σx = {X/(1#Ax)·_Y#Bx} o σy
= {X/(1#1#Z)·_X # Y·Z#1} o {Y/(1#Z)·_Y#Z}
= {X/ Z·_X #Y·Z#1} o {Y/(1#Z)·_Y#Z}
= {X/ Z·_X #((1#Z)·_Y#Z)·Z#1, Y/(1#Z)·_Y#Z}
= {X/ Z·_X #Z#1, Y/(1#Z)·_Y#Z}
= {X/ Z·_X #Z#1, Y/(1#Z)·_Y#Z}
25 November 2005 Foundations of Logic and Constraint Programming 17
Interpreting Unifiers
Hence, constraint X#X·Z = Y·Z#1 is satisfiable, since the unification of
termsX#X·ZandY·Z#1succeeds,returningthemostgeneralunifier
= {X/Z·_X #Z#1, Y/(1#Z)·_Y#Z}
Thisresultcanbeconfirmed:
(X#X·Z) = (Z·_X#Z#1)#(Z·_X#Z#1)·Z
= (Z·_X#Z#1)#Z·_X
= Z#1
(Y·Z#1) = ((1#Z)·_Y#Z)·Z#1)
= Z#1
Analysingtheunifierwenotethatthetwotermsunifywhenever Z=0andX = 1andYisarbitrary(Y =_Y) Z=1andY = 1 andXisarbitrary(X =_X)
Theunifierhasthereforethegroundinstances
{X/1, Y/0, Z/0}, {X/1, Y/1, Z/0},
{X/0, Y/1, Z/1}, {X/1, Y/1, Z/1}.
25 November 2005 Foundations of Logic and Constraint Programming 18
Digital Circuits Application
Asimpleexample:1. ModelcircuitbelowwithBooleanconstraints2. Howdoestheoutputrelates(symbolically)withtheinputs.
R1:Unifier1isobtainedbysolvingR1
C = 1 # A·B 1 ={C / 1 # A·B}
R2:Then1isappliedtoR2
R2’: R2 1 : D = (1#A·C){C/1#A·B}
D = (1#A·(1#A·B))
D = 1 # A # A·B
R1: C = 1 # A·B
R2: D = 1 # A·C
R3: E = 1 # B·C
R4: F = 1 # D·E
CR1 FR4
DR2
ER3
B
A
25 November 2005 Foundations of Logic and Constraint Programming 19
Digital Circuits Application
SolvingR2’: D = 1 # A # A·B unifier’2isobtained
’2 = {D / 1 # A # A·B}
2isobtainedbycompositionof2’with1
2 = 1
o 2’
= {C/1#A·B} o {D/1#A#A·B} = {C/1#A·B, D/1#A#A·B}
R3:Applying2toR3,then
R3’: R3 2 : E = (1#B·C) {D/1#A#A·B, C/1#A·B}: E = 1#B·(1#A·B): E = 1#B·(1#A·B)
SolvingR3’,unifier3’ isobtained
3’ = {E/1#B#A·B}
Now,3’iscomposedwith2
3 = 2
o 3’
= {E/1#B#A·B} o {D/1#A#A·B} o {C/1#A·B}= {E/1#B#A·B, D/1#A#A·B, C/1#A·B}
25 November 2005 Foundations of Logic and Constraint Programming 20
Digital Circuits Application
R4:Finally,beforesolvingR4 ,3isapplied
R4’: R4 3
: F = (1#D·E) {E/1#B#A·B, D/1#A#A·B, C/1#A·B}
: F = 1#(1#A#A·B)·(1#B#A·B)
: F = 1#1#B#A·B#A#A·B#A·B#A·B#A·B#A·B
: F = A # B
Now,R4’issolvedandunifier4’ isobtained
4’ = {F/A#B}
Composing4’with3
,itisobtained4,aunifierforalltheconstraints
4 = 3
o 4’
= {E/1#B#A·B, D/1#A#A·B, C/1#A·B}o{F/A#B}
= {E/1#B#A·B, D/1#A#A·B, C/1#A·B, F/A#B}
Byinterpreting4wemayconcludethatthiscircuitwith4nandgatesimplements
theexclusive-or,since
F / A # B.
25 November 2005 Foundations of Logic and Constraint Programming 21
CLP(B) in SICStus
OnceloadedSICStusPrologthemoduleonBooleanConstraintsisloaded
withdirective
:- use_module(library(clpb)).
BooleanConstraintsmaybespecifiedwithbuilt-inpredicatesat(E),where
equalityisspecifiedas‘=:=’andseveralBooleanoperatorscanbeused,
namely
C = or(A,B) specified as C =:= A+B
C = nor(A,B) specified as C =\= A+B
C = xor(A,B) specified as C =\= A#B
C = and(A,B) specified as C =:= A*B
C = nand(A,B) specified as C =\= A*B
C = not(A) specified as C =\= A
25 November 2005 Foundations of Logic and Constraint Programming 22
CLP(B) in SICStus
SomeExamples:
1. ?- sat(A#B=:=F).
sat(A =:= B#F)?
%ConstraintA#B=FissatisfiablewithunifierA/B+F
2. ?- sat(A*B=:=1#C*D).
sat(A=\=C*D#B)?
%ConstraintA·B=1+C·DissatisfiablewithunifierA/1+C·D+B
3. ?- sat(A#B=:=1#C*D), sat(C#D=:=B).
sat(B=:=C#D),
sat(A=\=C*D#C#D) ?
%ConstraintsA+B=1+C·DandB=C+Daresatisfiablewithunifier
{A/1+C·D+C+D, B/C+D}
25 November 2005 Foundations of Logic and Constraint Programming 23
CLP(B) in SICStus
Amorecompleteexample,relatedtothepreviouscircuit
| ?- circuit(A,B,[C,D,E],1).C = 1,E = A,sat(B=\=A),sat(D=\=A) ?
Note: Comparethisanswerwithunifier 5 = {E/1+B, D/B, C/1, F/1, A/1+B } foundbefore.
CG1
FG4
DG2
EG3
B
A:- use_module(library(clpb)).nand_gate(X,Y,Z):- sat(X*Y =:= 1#Z).
circuit(A,B,[C,D,E],F):- nand_gate(A,B,C), nand_gate(A,C,D), nand_gate(B,C,E), nand_gate(D,E,F).
25 November 2005 Foundations of Logic and Constraint Programming 24
CLP(Q) Application
Anotherdomainforwhichacompletesolverexistsisthatoflinearconstraints
overtherationalsorreals.TheintegrationofsuchasolverwithLPforms
theCLP(Q)orCLP(R)instanceoftheCLP(X)scheme.
CLP(Q)andCLP(R)differintheirapproachhandlearithmetics:
Ifthecoeficientsarerational(divisionbetweenintegers)thesolutiona
arealsorational.HenceCLP(Q)avoidsroundingerrorsbyhandling
properlywitharithmetics(“+”,”–”,“*”,“/”)overrationals(witharithmetics
withoutrounding
CLP(R)roundsrationalsasfloatingpointnumbers,andismore
“efficient”ifless“precise”
Theseconstraintsarequitecommoninapplications.Evenwhenconstraints
arenotlinear,problemsareoften“linearised”(i.e.modelledwithlinear
constraintssuchtahttheerrorsareacceptable),giventheveryefficientway
ofsolvingtheseconstraints,basedontheSIMPLEXalgorithm.
25 November 2005 Foundations of Logic and Constraint Programming 25
CLP(Q) : Example
Contraints:% Minimum required flow x 6, z 10 % minimum flow% flow capacity of arcs a 5, b 3, c 7, d 2, e 8, f 6% processing capacity of nodes x 7, y 9, a + b 9, c 8, a + b + d 9, e + f 13% flow maintenance x = a, y = b + c, a + b + d = e, c = d + f, e + f = z% non-negative constraints x, y ,z, a, b, c, d, e, f 0
7
8
9 9
13
5/a
2/d 8/e
6/f
3/b
7/c
x
y
z
The following problem illustrates a typical use
oflinearconstraints:
Problem (Network Management):
Findthevalueoftrafficfrompointsx,ytoz
such that the traffic does not exceed the
flow capacity of each arc, nor the
processingcapacityofeachnode.
25 November 2005 Foundations of Logic and Constraint Programming 26
CLP(Q) Solver: SIMPLEX
TheSIMPLEXalgorithmaimsatconvertingalllinearconstraintsintoasolved
form, composed of equality constraints on linear expressions. This
conversionisdoneintwosteps.
1. All inequality constraints on decision variables are converted into equality
constraintswiththeadditionof“slack”(non-negative)variables
a X1 +...+ an Xn ≤ b a X1 +...+ an Xn + S = b
a X1 +...+ an Xn ≥ b a X1 +...+ an Xn - S = b
2. In general m constraints on n decision variables are converted into m
constraints on k+n non-negative variables, where k m ( k = m if all
constraintsareinequalityconstraints).
3. Asolvedformisobtainedifapartitioncanbefoundonthek+nvariablesinm
basicvariablesXi(i1..n)andp = k+n-mnonbasicvariablesYj(j1..p),
suchthatthemconstraintscanbewrittenas
Xi = di + ci1 Y1+ ... + cip Yp (foralli1..n)
whereallfreecoefficientsdiarenon-negative.
25 November 2005 Foundations of Logic and Constraint Programming 27
SIMPLEX: Geometric Interpretation
X2 = 0
X2
X1
X3 = 0
X5 = 0
X1 = 0
X4 = 0
X3 = 8 - 2 X1 - X2X4 = -3 + X1 + X2X5 = 5 + X1 - X2
x1 = 1 - x3/3 + x5/3x2 = 6 - x3/3 - 2 x5/3x4 = 4 - 2 x3/3 - X5/3
X1 = 5 - X3 - X4X2 = -2 + X3 + 2 X4X5 = 12 - 2 X3 - 3 X4
X2 = 5 + X1 - X5X3 = 3 - 3 X1 + X5X4 = 2 + 2 X1 - X5
2 X1 + X2 ≤ 8 X1 + X2 ≥ 3 X1 - X2 ≥ -5 X1 , X2 ≥ 0
2 X1 + X2 + X3 = 8 X1 + X2 - X4 = 3 X1 - X2 - X5 = -5
25 November 2005 Foundations of Logic and Constraint Programming 28
SICStus CLP(Q)/CLP(R) Solvers
SICStusPrologsupportsconstraintsolvingovertheRational/Realnumbers.As
for Booleans, to handle these constraints, a module for CLP(Q) or CLP(R)
mustbeloaded,withdirectives:
:- use_module(user:library(clpq)).
:- use_module(user:library(clpr)).
ContraintsmaynowbespecifiedwiththeusualPrologsyntaxbutinside{}.Forexamplethepreviousproblemmaybedirectlyspecifiedas
p1([X1,X2]) :-
{2*X1 + X2 =< 8, X1 + X2 >= 3, X1 - X2 >= -5 },
{ X1 >= 0, X2 >= 0 }.
orspecifiedwithexplicitslackvariables
p2([X1,X2,X3,X4,X5]) :-
{2*X1+X2+X3 = 8, X1+X2–X4 = 3, X1-X2–X5 = -5 },
{ X1 >= 0, X2 >= 0, X3 >= 0, X4 >= 0, X5 >= 0} .
25 November 2005 Foundations of Logic and Constraint Programming 29
SICStus CLP(Q)/CLP(R) Solvers
Once defined these programs can be run. Answers projected to the called
variables,withsomeextravariablesincludedwhennecessary
p1([X1,X2]) :-
{2*X1 + X2 =< 8, X1 + X2 >= 3, X1 - X2 >= -5 },
{ X1 >= 0, X2 >= 0 }.
| ?- p1([X1,X2]).
{X1+1/2*X2=<4},
{X1>=0},
{X2>=0},
{X1+X2>=3},
{X1-X2>= -5} ?
X2 >= 0
X2
2 X1 + X2 = 8
X1 - X2 = -5X1 >= 0
X1 + X2 = 3
X1
25 November 2005 Foundations of Logic and Constraint Programming 30
SICStus CLP(Q)/CLP(R) Solvers
Thesolvedformismoreeasily(?)identifiedwiththeexplicitslackvariables.
p2([X1,X2,X3,X4,X5]) :-
{2*X1+X2+X3 = 8, X1+X2–X4 = 3, X1-X2–X5 = -5 },
{ X1 >= 0, X2 >= 0, X3 >= 0, X4 >= 0, X5 >= 0} .
| ?- p2([X1,X2,X3,X4,X5]).
{X5=9-3/2*X2-1/2*X3},
{X4=1+1/2*X2-1/2*X3},
{X1=4-1/2*X2-1/2*X3},
{X2+X3=<8},
{X2+1/3*X3=<6},
{X2>=0},
{X3>=0},
{X2-X3>= -2} ?
SolvedformidentifiesX1 = 4, X2 = 0
X2 >= 0
X2
2 X1 + X2 = 8
X1 - X2 = -5X1 >= 0
X1 + X2 = 3
X1
25 November 2005 Foundations of Logic and Constraint Programming 31
SICStus CLP(Q)/CLP(R) Solvers
Ofcourse,iftheproblemhasnosolutionstheanswerisno!
p3([X1,X2]) :-
{2*X1 + X2 >= 8, X1 + X2 =< 3, X1-X2 =< -5 },
{ X1 >= 0, X2 >= 0} .
| ?- p3([X1,X2]).
no ?
X2 >= 0
X2
2 X1 + X2 = 8
X1 - X2 = -5X1 >= 0
X1 + X2 = 3
X1
25 November 2005 Foundations of Logic and Constraint Programming 32
SICStus CLP(Q)/CLP(R): Example
Example:
Acertainamountofmoneyislentatsomeinterestrateforanumberoftime
periods,tobepayedwithconstantinstalments.
Model
Assumingthat Iisthenumberoftimeperiodsremainingtopaythedebt Di representsthedebtatthebeginingoftimeperiodi.
Ristheinterestrate(inpercentagepoints) Pisthe(constant)instalmenttobepayedattheendofeachtimeperiod
thenwehavethefollowingrelations:
Thedebtatthebeginingofaperiodisthedebtatthebeginingofthepreviousperiod,increasedbytheinterest,lessthepaymentmade.
Di = Di+1 * (1 +R/100) – P for i > 1
Nodebtshouldexistattheendofthelasttimeperiodlasttimeperiod
0 = D1 * (1 +R/100) – P
25 November 2005 Foundations of Logic and Constraint Programming 33
SICStus CLP(Q)/CLP(R): Example
TheseconstraintscanbeeasilyexpressedinCLP(Q)/CLP(R)asshowninthe
programsbelow.
Notice that such program could not be easily converted to pure Prolog, in
statementslikeV is Exp,sinceonedoesnotknowwhatvaluesaregivenand
whatareknow.
% 0 = D1 * (1 +R/100) – P debt(Debt, Rate, TimeLeft, Payment):- { TimeLeft = 1, Payment = Debt * (1 + Rate/100) }.
% Di = Di+1 * (1 +R/100) – P for i > 1debt(Debt, Rate, TimeLeft, Payment):- { TimeLeft > 1, NextTimeLeft = TimeLeft - 1, NextDebt = Debt * (1 + Rate/100) – Payment }, debt(NextDebt, Rate, NextTimeLeft, Payment).
25 November 2005 Foundations of Logic and Constraint Programming 34
SICStus CLP(Q)/CLP(R): Example
Someinteractionwiththeprogram
Whatyearlypaymentisduewhen100unitsarelentfor7yearsata5%
interestrate.Whatisthetotalpayment?
| ?- debt(100,5,7,P), {T = 7* P}.
P = 17.28198184461708,
T = 120.97387291231955 ?
Whatamountofmoneycanbeborrowedbysomeonethatiswillingtopay
afixedinstalmentof10unitsfor7years,whnetheinterestrateis5%?
| ?- debt(D,5,7,10).
D = 57.86373397397567 ?
Whatistherelationshipbetweentheyearlypaymentandtheinitialdebt,
when7yearsareusedandtheinterestrateis5%?
| ?- debt(D,5,7,P).
{P=0.17281981844617078*D} ?
25 November 2005 Foundations of Logic and Constraint Programming 35
SICStus CLP(Q)/CLP(R): Example
ItisimportanttonoticethatCLP(Q)/CLP(R)isonlycompletewhenthe
constraintsarelinear.Whentheyarenottheyarefrozenintheconstraintstore,
pendingfurtherinstantiation
Whatistherelationbetweentheyearlypaymentandtheinitialdebt,when
7yearsareusedandtheinterestrateisR%
| ?- debt(D,R,7,10).
clpr:{10.0-D-0.01*(R*D)+_A=0.0}, % 7 years to go
clpr:{10.0-0.01*(_B*R)-_B=0.0}, % 6 years to go
clpr:{10.0+_C-0.01*(_A*R)-_A=0.0}, % 5 years to go
clpr:{10.0+_D-0.01*(_C*R)-_C=0.0}, % 4 years to go
clpr:{10.0+_E-0.01*(_D*R)-_D=0.0}, % 3 years to go
clpr:{10.0+_F-0.01*(_E*R)-_E=0.0}, % 2 years to go
clpr:{10.0+_B-0.01*(_F*R)-_F=0.0} ? % 1 years to go