Reputation: 4703
Consider the following setup:
:- use_module(library(chr)).
:- chr_constraint
a/1,
b/1.
% really there will be many of these, possibly 100s
% some rules about how to replace as with bs, e.g.,
a(1),a(1) <=> b(2).
% a way to decompose, e.g., b(2) <=> b(1), b(1)
a(X) <=> X #> 1, Y #= X-1 | a(Y), a(1).
b(X) <=> X #> 1, Y #= X-1 | b(Y), b(1).
% except I have to write these for all 100+ variables
I know prolog is capable of meta-programming, and I believe it could be used to generate the x(X)
decompositions above, but I'm not at all sure how to do it. I got close once using =..
to pull apart and put back together calls, but then I had to write something like n(a(2))
everywhere. Ideally, I would write n(a)
once and the correct constraint rule would be added (asserted?):
It would make more sense to be able to do something like
n(X) <=> %... or possibly :-
n(a).
n(b).
% a(X) <=> ... and b(X) <=> ... are added to the "database" of rules
If it were lisp, I could write the macro to do it, I think. And prolog is supposed to be homoiconic like lisp is, so it's theoretically achievable. I just don't know how.
How do I write the decomposer "macro" following something similar to the above style?
Upvotes: 2
Views: 86
Reputation: 4797
I think this solves the problem in a simple way.
:- chr_constraint mycon/2, fuel/0, ore_add/1, total_ore/1.
mycon(a,1),mycon(a,1) <=> mycon(ore,9).
mycon(b,1),mycon(b,1),mycon(b,1) <=> mycon(ore,8).
mycon(c,1),mycon(c,1),mycon(c,1),mycon(c,1),mycon(c,1) <=> mycon(ore,7).
mycon(ab,1) <=> mycon(a,3),mycon(b,4).
mycon(bc,1) <=> mycon(b,5),mycon(c,7).
mycon(ca,1) <=> mycon(c,4),mycon(a,1).
fuel <=> mycon(ab,2),mycon(bc,3),mycon(ca,4).
%Decompose foo/N into foo/1s
mycon(Type,X) <=> X>1,Y#=X-1|mycon(Type,Y),mycon(Type,1).
total_ore(A), total_ore(Total) <=> NewTotal #= A + Total, total_ore(NewTotal).
ore_add(A) ==> total_ore(A).
mycon(ore,1) <=> ore_add(1).
Cleaner look with operator:
:- op(900, xfx, (of)).
:- chr_constraint fuel/0, ore_add/1, total_ore/1,of/2.
1 of a,1 of a <=> 9 of ore.
1 of b,1 of b,1 of b <=> 8 of ore.
1 of c,1 of c,1 of c,1 of c,1 of c <=> 7 of ore.
1 of ab <=>3 of a,4 of b.
1 of bc <=> 5 of b,7 of c.
1 of ca <=> 4 of c,1 of a.
fuel <=> 2 of ab,3 of bc,4 of ca.
%Decompose foo/N into foo/1s
X of Type <=> X>1,Y#=X-1|Y of Type,1 of Type.
total_ore(A), total_ore(Total) <=> NewTotal #= A + Total, total_ore(NewTotal).
ore_add(A) ==> total_ore(A).
1 of ore <=> ore_add(1).
Upvotes: 0