Replace certain constraints in the constraint store of CHR with other constraints

Suppose in a state, state1, I have a list of constraints in the constraint store:

state1 = [p(a,1), p(b,0), p(a,0), p(b,1), p(b,0)]

Now I have a constraint c(b,1) which states that all p(b,0) should be replaced by p(b,1). Thus we should obtain a new state state2 such that:

state2 = [p(a,1), p(b,1), p(a,0), p(b,1), p(b,1)]

How can this be done for any constraint of the form c(X, Y), and any list of constraints of the form p(X, Y)?

This can probably be done with just 2 or 3 lines in CHR, but I do not know how to do this. Thanks in advance.

1 Like

Perhaps I misunderstanding what you mean by list of constraints, i.e. a single constraint which contains a list, or an actual list of individual constraints…

The following rule should work.

apply@ c(X,Y) \ p(X,0) <=> p(X,Y).
       c(_,_) <=> true.

For clarity, let us consider the following program with your rules:

:- chr_constraint c/2, p/2.

load_it :- p(a,1), p(b,0), p(a,0), p(b,1), p(b,0). 

c(X,Y) \ p(X,_) <=> p(X,Y).
c(_,_) <=> true.

Notice that, in your rules, I have replaced p(X,0) with p(X,_) since I want to do this for any constraint of the form p(X, Y) and c(X, Y). For instance, I might have c(b,0), i.e., replace all p(b,1) with p(b,0). The same rules should work for this case also.

Now if I query ?- load_it, c(b,1). your solution will go into an infinite loop.

I should get the following:

?- load_it, c(b,1). 
p(a,1), 
p(b,1), 
p(a,0), 
p(b,1), 
p(b,1).

@Ian I think the rules that you provided are not the solution to this problem.

The rules do work for the original problem :smiley:
You stated

Now I have a constraint c(b,1) which states that all p(b,0) should be replaced by p(b,1) .

Your amended rules will change p(b,4) to p(b,1) !

If the new problem is now c(X,Y) changes any p(X,_) to p(X,Y) then you will need to amend the rules to prevent the infinite loop.
e.g.

c(X,Y) \ p(X,V) <=> V \= Y | p(X,Y).
2 Likes

@Ian You are correct. Thanks for the help :slight_smile: