我正在尝试创建一个自定义的clpfd全局约束,该约束与all_diferent约束非常相似。
约束应只允许包含不同非零项目的列表(因此可以有多个零)。
这是SICSTUS Prolog中的一个有效示例:
:- use_module(library(clpfd)).
mask([], [], []).
mask([H1|T1], [H2|T2], [P|R]) :-
P #= H1 * H2, mask(T1, T2, R).
diff(L) :-
diff_rec(L, L).
diff_rec([], _).
diff_rec([H|T], L) :-
fd_global(diff_zero(H, T, L), no_state, [val(H)]),
diff_rec(T, L).
:-multifile clpfd:dispatch_global/4.
clpfd:dispatch_global(diff_zero(X, Tail, List), S, S, Actions):-
(ground(X) ->
filter_diff(List, X, Tail, Actions)
;
Actions = []
).
filter_diff(_, 0, _, [exit]).
filter_diff([], _X, _Tail, [exit]).
filter_diff([Y|T], X, Tail, Actions):-
(T==Tail ->
Actions = RestActions
;
fd_set(Y, SetY),
fdset_del_element(SetY, X, NewSetY),
Actions = [Y in_set NewSetY | RestActions]
),!,
filter_diff(T, X, Tail, RestActions).
all_diff_zero(L, X) :-
length(L, N),
length(X, N),
domain(X, 0, 1),
mask(L, X, M),
diff(M),
!,
labeling([], X).
对于给定的列表,all_diff_zero
谓词应该找到一个二进制掩码,该掩码与原始列表一起给出具有所有不同非零项目的列表。
在用filter_diff(_, 0, _, [exit]).
注释掉该行之后,diff
像往常一样使用所有不同的约束(例如all_diff_zero([ 3 , 1 , 1 ], X).
仅给我X = [1,0,1]; X = [1,1,0]
)。
但是,与此行完全不同或为零的约束根本不起作用:
?- all_diff_zero([ 3 , 1 , 1 ], X).
X = [0,0,0] ? ;
X = [0,0,1] ? ;
X = [0,1,0] ? ;
X = [0,0,0] ? ;
X = [0,0,1] ? ;
X = [0,1,0] ? ;
X = [0,1,0] ? ;
X = [1,0,0] ? ;
X = [1,0,0] ? ;
X = [1,0,1] ? ;
X = [1,0,0] ? ;
X = [1,0,0] ? ;
X = [1,0,1] ? ;
X = [1,0,0] ? ;
X = [1,0,0] ? ;
X = [1,0,1] ? ;
X = [1,0,1] ? ;
X = [1,0,1] ? ;
X = [1,1,0] ? ;
X = [1,1,0] ? ;
X = [1,1,1] ? ; % wrong
X = [1,1,0] ? ;
X = [1,1,1] ? ; % wrong
X = [1,1,0] ? ;
X = [1,1,1] ? ; % wrong
X = [1,1,0] ? ;
X = [1,1,1] ? ; % wrong
请注意,所需的输出是:
?- all_diff_zero([ 3 , 1 , 1 ], X).
X = [0,0,0] ? ;
X = [0,0,1] ? ;
X = [0,1,0] ? ;
X = [1,0,0] ? ;
X = [1,1,0] ? ;
X = [1,0,1] ? ;