This exercise asked me to find the best combination of three products, given the prices and specific combinations to avoid. The textbook employs assertz
and retractall
to emulate a state variable.
price(a1, 1900).
price(a2, 750).
price(a3, 900).
price(b1, 300).
price(b2, 500).
price(b3, 450).
price(b4, 600).
price(c1, 700).
price(c2, 850).
incompatible(a2, c1).
incompatible(b2, c2).
incompatible(b3, c2).
incompatible(a2, b4).
incompatible(a1, b3).
incompatible(a3, b3).
:- dynamic bound/1.
bound(5000).
solution(A, B, C, P) :-
member(A, [a1, a2, a3]),
price(A, PA),
member(B, [b1, b2, b3, b4]),
\+ incompatible(A, B),
price(B, PB),
P0 is PA + PB,
bound(Bound),
write('Current bound: '), writeln(Bound),
P0 =< Bound,
member(C, [c1, c2]),
\+ incompatible(A, C),
\+ incompatible(B, C),
price(C, PC),
P is PA + PB + PC,
P =< Bound,
retractall(bound(_)),
assertz(bound(P)).
- Is it possible to use branch and bound in Prolog without resorting to dynamic predicates?
- Is there a consensus on state variables in Prolog?
- Is there a way to restrict the scope of a state variable (or whatever the proxy would be) to a single rule?