Prolog 找到给定格式中所有可能的单词组合

Prolog 找到给定格式中所有可能的单词组合,prolog,substitution,constraint-programming,Prolog,Substitution,Constraint Programming,我有10万行长的字典: w([w,o,r,d]). w([h,a,p,p,y]). w([q,u,e,s,t,i,o,n]). ... 现在我正在编写一个脚本,它将返回所有可能的单词,这些单词符合给定的格式 例如: w([A,B,C]), w([B,C]), A \== B, A \== C, B \== C. 我找到了使所有变量都不同的来源: alldif([]). alldif([E|Es]) :- maplist(dif(E), Es), alldif(Es). 因此,我

我有10万行长的字典:

w([w,o,r,d]).
w([h,a,p,p,y]).
w([q,u,e,s,t,i,o,n]).
...
现在我正在编写一个脚本,它将返回所有可能的单词,这些单词符合给定的格式

例如:

w([A,B,C]), w([B,C]), A \== B, A \== C, B \== C.
我找到了使所有变量都不同的来源:

alldif([]).
alldif([E|Es]) :-
   maplist(dif(E), Es),
   alldif(Es).
因此,我现在呼吁:

w([A,B,C]), w([B,C]), alldif([A,B,C]).
现在我想要变量A是[A,e,I,o,t,l]中的一个。我可以通过以下方式实现:

member(A, [a,e,i,o,t,l]).
但使用约束编程是否更快

A in [a,e,i,o,t,l]

我现在有点困了。其想法是在.txt文件中逐行生成所有可能的选项

我使用以下方法将单词连接到语句中:

g([A,B,C], W1), g([B,C], W2), alldif([A,B,C]), buildStat([W1,W2], Statement).
其中:

g(Format, Word):-
    list_to_set(Format, Uniques),
    alldif(Uniques),
    w(Format),
    atomic_list_concat(Format, '', Atom), atom_string(Atom, Word).

insertSpaces([A], [A]).
insertSpaces([Word | Rest], OutWords):-
    insertSpaces(Rest, OutWordsRest),
    OutWords = [Word, " " | OutWordsRest].


buildStat(Words, Statement):-
    insertSpaces(Words, OutWords),
    with_output_to(atom(Statement), maplist(write, OutWords)).
但我不知道如何将所有可能的语句逐行保存到文件中。
非常感谢您的帮助。

发布所有解决方案的一个简单技巧是通过
false/0强制回溯

例如,假设您有一个谓词,该谓词在回溯时生成所有解决方案:

?- solution(S).
“错误”解决了所有问题。你能帮我找到更快的方法吗(要请求所有不同的变量,例如指定A必须是[A,e,i,o],或者首先在字典中查找单词?)。另外,尝试使用
time/1
来测量所需的时间,例如
?-time(您的目标)。
。这将帮助您找出哪种方法更快。 ?- solution(S). ?- solution(S), print_solution(S), false. $ prolog --goal 'ignore((solution(S),portray_clause(S),false)),halt' > output.txt