PROLOG CLPFD How to express this via constraints?
Reification involves separate constraints (#<==>/2
, #==>/2
etc.), you can use them for example like:
example(Ls) :-
Ls = [X,Y],
Ls ins 1..2,
X #= 1 #<==> B1,
Y #= 1 #<==> B2,
X #= 2 #<==> B3,
Y #= 2 #<==> B4,
Cost #= max(B1*3 + B2*5, B3*3 + B4*5),
labeling([min(Cost)], Ls).
Sample query and its result:
?- example(Ls).
Ls = [1, 2] ;
Ls = [2, 1] ;
Ls = [1, 1] ;
Ls = [2, 2] ;
false.
As an alternative to using reification you could also use additional arithmetic constraints for "capturing" equality in an expression:
example([X,Y]) :-
X in 1..2,
Y in 1..2,
Cost #= max(3*(1-min(1,abs(X-1))) + 5*(1-min(1,abs(Y-1))),
3*(1-min(1,abs(X-2))) + 5*(1-min(1,abs(Y-2)))),
labeling([min(Cost)], [X,Y]).
Note that the expression inside Cost #= max(...)
can be slightly simplified.
Sample use:
?- example(Ls).
Ls = [1,2]
; Ls = [2,1]
; Ls = [1,1]
; Ls = [2,2]
; false.