且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Prolog-计算列表中的重复次数

更新时间:2023-11-26 07:57:04

在我看来,您已经在那里.您可以简单地将谓词换成另一种说法:

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.