【发布时间】:2018-05-01 15:57:15
【问题描述】:
给定一个字母列表,我试图找出可以用这些字母组成的最长单词。
include('words.pl').
word_letters(Word, Letters) :- atom_chars(Word, Letters).
cover([],_).
cover([Head1|Tail1], List2) :- select(Head1,List2, List3), cover(Tail1, List3).
solution(ListLetters, Word, Length) :- word(Word),
word_letters(Word,LettersWord),
length(LettersWord, Length),
cover(LettersWord,ListLetters).
topsolution(Letters, Word, LMax) :- solution(Letters, Word, LMax).
topsolution(Letters, Word, LMax) :- select(_, Letters, RemainingLetters),
topsolution(RemainingLetters, Word, LMax).
word_letters 谓词转换字母列表中的给定单词。 覆盖谓词告诉给定列表是否包含在第二个列表中。
?-cover([a,b,c], [b, a, a, c])
true
求解谓词为给定的字母列表找到所有可以用这些字母组成的单词及其长度。
我的问题是 topsolution 谓词应该只返回最大长度的解决方案,但它的工作原理就像解决方案一样。
您能帮我理解如何制作顶级解决方案,以便它只输出最大长度的单词吗?
这是我的单词数据库:tinyurl.com/prolog-words
【问题讨论】:
-
只需要
once(topsolution(...))吗? -
它不是以最长的单词开头的。
-
你的意思是
:- include('words.pl').? -
不幸的是,
topsolution/3正如您所定义的那样,它并没有为solution/3所做的添加任何内容。感谢cover/2,solution/3已经尝试排除所有排列。在topsolution/3中您需要做的是从solution/3获取结果列表并找到最长的。可能使用findall/3或setof/3或bagof/3。 -
我使用另一个谓词解决了我的问题。
topsolution(Letters, Word, Lmax) :- length(Letters, N1), topsolutionCount(Letters, Word, Lmax, N1).topsolutionCount(_, _,_,0).topsolutionCount(Letters, Word, N, N) :- solution(Letters, Word, N).topsolutionCount(Letters, Word,Lmax, N) :- N1 is N-1, topsolutionCount(Letters, Word, Lmax, N1).
标签: prolog