我无法生成符合特定条件的所有列表。
city(new_york, 47).
city(chicago, 100).
all_unique([]).
all_unique([H|T]) :- H = [] ; (not(member(H, T)), all_unique(T)).
cities([Head|Tail]) :-
length(Tail, L),
L < 2,
city(Head, _A),
(Tail = [] ; cities(Tail)).
当我发出查询cities(L)
时,我希望它生成所有城市列表,其最大长度为2且不重复。它现在做的是返回所有可能的列表,然后继续尝试明显不符合标准的列表。
?- cities(L).
L = [new_york] ;
L = [chicago] ;
L = [new_york, new_york] ;
L = [new_york, chicago] ;
L = [chicago, new_york] ;
L = [chicago, chicago] ;
ERROR: Out of global stack
?-
如何告诉Prolog不要尝试太长或重复项目的列表?
答案 0 :(得分:3)
all_unique/1
的定义最好基于prolog-dif:
all_unique([]).
all_unique([E|Es]) :-
maplist(dif(E), Es),
all_unique(Es).
根据meta-predicate maplist/2
,您可以像这样定义cities/1
:
city_(new_york, 47).
city_(chicago, 100).
city(C) :-
city_(C, _).
cities(List) :-
length(Ref, 2),
append(List, _, Ref),
all_unique(List),
maplist(city, List).
示例查询:
?- cities(Xs).
Xs = [] ;
Xs = [new_york] ;
Xs = [chicago] ;
Xs = [new_york, chicago] ;
Xs = [chicago, new_york] ;
false. % terminates universally