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

时间:2017-07-01 10:56:41

标签: prolog substitution constraint-programming

我有100 000行长词典:

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]

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)).

但我不知道如何逐行将所有可能的语句保存到文件中。 帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

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

例如,假设你有一个谓词可以产生回溯的所有解决方案:

?- solution(S).

您可以发出所有解决方案,如下所示:

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

您必须定义print_solution/1,因为您希望产生所需的格式。

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

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