:-consult(words.pl). % words is basically a big database of the
% 30.000 most used words in the english language
topsolution([], _, P) :- %basecase, in case the given list of letters is
%empty, output no word and give the amount of letters
%and call it P
word(X), %sees if X is a word
P = 0.
topsolution(WordList, X, P) :- %Makes the longest word it can out of a list
%of letters and outputs said word as X, and the
%amount of letters it has as P
Y = 0,
solution(WordList, X, Y), %Determines what words you can make with a given
%list of letters and a given length of said word
Y1 is Y + 1,
solution(WordList, X, Y1), %Determines the longest word of Y + 1
wordLength(P, X). %Defines how many letters a word X has and calls that amount P这就是我为了找到那个单词而写的代码。我正在努力解决的唯一问题是我找不到一种方法来停止递归。目前,如果我输入:
?- topsolution([g,i,g], Word, Y). Prolog输出如下:
false即使它应该输出:
Word = gig
Y = 3
true我知道它为什么这么做。这是因为Y将不断增加1,直到它达到Y= 4。因为在只有3个字母的列表中没有4个字母的可能单词。这显然是失败的。
那么你们建议如何解决这个问题呢?如果prolog遇到无法输出单词的情况,我应该如何告诉prolog它应该停止?
发布于 2017-09-15 23:13:46
您应该非常怀疑您的基本情况,因为单一值警告。将Prolog中的单例视为错误是很重要的,因为它们总是代表您和Prolog之间的误解。
我认为你这里的基本情况是错误的。当Prolog不能进行统一时,它将输出false;这正是应该发生的。如果你调用topsolution([g,g,g,g], Word, P),它应该输出false,而不是说P = 0而不是Word。没有解决方案。说P = 0就是说“我找到了一个长度为0的解决方案,但我不会告诉你它是什么。”说“我没有找到解决方案”会更好。
我认为你真的有两个案例:
我找到了一个基于我这里的字母排列的单词,我通过在我这里的字母的子集上尝试#1找到了一个单词
你的基本情况实际上是#1:我手头上的是一个单词的字母排列,下面是这个单词:
topsolution(Letters, Word, P) :-
permutation(Letters, WordLetters), % permute the letters
atom_chars(Word, WordLetters), % make a permuted atom
word(Word), % guard: it's a word
length(Letters, P). % what's its length?然后你的归纳案例是去掉一个字母,然后再试一次:
topsolution(Letters, Word, P) :-
select(_, Letters, RemainingLetters), % remove a letter
topsolution(RemainingLetters, Word, P). % try again对于序列中的每个字母,当您在穷尽所有排列后进入第二个谓词体时,递归将停止。select(_, [], _)为false。所以这里不需要担心P = 0的情况。
https://stackoverflow.com/questions/46204720
复制相似问题