2

考虑以下设置:

:- 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 一样的谐音,所以理论上是可以实现的。我只是不知道怎么做。

如何按照类似于上述风格的方式编写分解器“宏”?

4

1 回答 1

0

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).
于 2019-12-15T22:24:59.890 回答