List 必须从给定字母列表中找出可能最长的单词
这就是我用来找到这个词的代码。我正在努力解决的唯一问题是,我无法找到一种方法使递归停止。当前如果我输入:List 必须从给定字母列表中找出可能最长的单词,list,prolog,List,Prolog,这就是我用来找到这个词的代码。我正在努力解决的唯一问题是,我无法找到一种方法使递归停止。当前如果我输入: :-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
:-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
Prolog输出以下内容:
?- topsolution([g,i,g], Word, Y).
即使它应该输出:
false
我知道它为什么会这样。这是因为Y将继续增加1,直到它达到Y=4。因为在只包含3个字母的列表中,没有可能包含4个字母的单词。这显然是失败的
你们建议怎么解决这个问题?如果遇到无法输出单词的情况,我该如何告诉prolog它应该停止?由于单例值警告,您应该非常怀疑您的基本情况。对于您来说,将Prolog中的单例视为错误是很重要的,因为它们总是表示您和Prolog之间的误解 我认为你的基本情况是错误的。当Prolog无法统一时,将输出
false
;这正是应该发生的。如果您调用topsolution([g,g,g,g],Word,P)
,它应该输出false
,而不是说P=0
,对Word一无所知。没有解决办法。说P=0
就是说“我找到了长度为0的解决方案,但我没有告诉你它是什么。”最好说“我没有找到解决方案。”
我认为你真的有两种情况:
Word = gig
Y = 3
true
然后,您的归纳案例是去掉一个字母,然后重试:
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?
对于序列中的每个字母,在用尽所有排列之后,当您进入第二个谓词体时,递归将停止<代码>选择(_,[],_)为false。因此,这里没有需要担心的
P=0
案例。如果没有solution/3的代码,调试这个将非常困难。
topsolution(Letters, Word, P) :-
select(_, Letters, RemainingLetters), % remove a letter
topsolution(RemainingLetters, Word, P). % try again