[英]Generate decomposition constraints for constraints
考慮以下設置:
:- 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
我知道 prolog 能夠進行元編程,並且我相信它可以用來生成上面的x(X)
分解,但我完全不確定如何去做。 我曾經使用=..
將調用分開並重新組合在一起,但后來我不得不到處寫類似n(a(2))
東西。 理想情況下,我會寫一次n(a)
並添加正確的約束規則(斷言?):
能夠做類似的事情會更有意義
n(X) <=> %... or possibly :-
n(a).
n(b).
% a(X) <=> ... and b(X) <=> ... are added to the "database" of rules
如果是 lisp,我想我可以編寫宏來做到這一點。 而且 prolog 應該像 lisp 一樣是同形的,所以理論上是可以實現的。 我只是不知道如何。
如何按照類似於上述風格的方式編寫分解器“宏”?
我認為這以一種簡單的方式解決了問題。
:- 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).
操作員看起來更干凈:
:- 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).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.