Prolog - count repetitions in list
list, prolog
Solution
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).
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.
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.
Problem
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). ``` So the query `?- count_repetitions([yes],[yes,and,yes,and,no], X).` would give `X = 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?