Prolog-计算列表中的重复次数 [英] Prolog - count repetitions in list

查看:151
本文介绍了Prolog-计算列表中的重复次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试浏览列表并计算给定单词出现的次数.到目前为止,我已经知道了:

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.

这似乎起作用.现在,我需要编写一个谓词,该谓词以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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆