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

Find all possible combinations of words in given format

我有 100 000 行长的字典:

w([w,o,r,d]).
w([h,a,p,p,y]).
w([q,u,e,s,t,i,o,n]).
...

现在我正在编写一个脚本,它将 return 所有符合给定格式的可能单词。

例如:

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]

all_different([A,B,C]).

我现在有点卡住了。这个想法是在 .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).

你可以像这样发出所有个解决方案:

?- solution(S),
   print_solution(S),
   false.

您必须在此处定义 print_solution/1 以产生您想要的格式。

例如,您可以将此类解决方案打印到标准输出,然后 pipe 将输出输出到文件。具体细节取决于您的 Prolog 系统,可能如下所示:

$ prolog --goal 'ignore((solution(S),portray_clause(S),false)),halt' > output.txt