Prolog - 计算列表中的重复次数 [英] Prolog - count repetitions in list
问题描述
我正在尝试查看列表并计算给定单词出现的次数.到目前为止,我已经有了这个:
I'm trying to look through a list and count the number of times a given word appears. I've got this so far:
count_repetitions([_], [], 0).
count_repetitions([Word], [Word|Tail], Count):-
count_repetitions([Word], Tail, X),
Count is X + 1.
count_repetitions([Word], [Z|Tail], Count):-
Word = Z,
count_repetitions([Word], Tail, Count).
所以查询 ?- count_repetitions([yes],[yes,and,yes,and,no], X).
将给出 X = 2
.
So the query ?- count_repetitions([yes],[yes,and,yes,and,no], X).
would give X = 2
.
这似乎有效.现在我需要编写一个谓词,以X = [(yes - 2)]
的形式输出一个包含搜索词及其出现次数的列表.我完全被困住了,有什么建议吗?
This appears to work. Now I need to write a predicate that outputs a list with the search word and the number of times it appears, in the form X = [(yes - 2)]
. I'm completely stuck, any suggestions?
推荐答案
在我看来,你已经在那里了.您可以简单地将谓词包装在另一个语句中:
You are there, already, it seems to me. You could simply wrap your predicate in another one saying:
word_repetitions(Word, List, [(Word-Count)]) :-
count_repetitions(Word, List, Count).
请注意,Word-Count
对不需要括号或方括号:
Note that you don't need the parenthesis or the brackets around the Word-Count
pair:
word_repetitions(Word, List, Word-Count) :-
count_repetitions(Word, List, Count).
(但如果你坚持,你可以使用它们).
(but you can use them if you insist).
在您的原始谓词上,重命名以反映差异:
On your original predicate, renamed to reflect the differences:
list_word_reps([], Word, Word-0).
list_word_reps([W|Rest], Word, Word-Reps) :-
list_word_reps(Rest, Word, Word-Reps0),
( W == Word
-> Reps is Reps0 + 1
; Reps = Reps0
).
?- list_word_reps([yes,no,yes,no,maybe,yes], yes, X).
X = yes-3.
列表出现在单词之前的原因是谓词变得确定性.使用 if-then-else 而不是两个不同的子句也是如此.如果您愿意,您可以将答案放在一个列表中(只需将参数括在括号中),但同样,这是不必要的.
The reason why the list comes before the word is that the predicate then becomes deterministic. Same goes for using the if-then-else instead of two different clauses. You can put the answer in a list if you want to (just wrap the argument in brackets) but again, it is unnecessary.
这篇关于Prolog - 计算列表中的重复次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!