So i have a list of words and counters:
[("word1", 1), ("word2", 1)]
and I was wondering how I would increment the counter for a word i add into that list, for example:
- If the word was already in the list, increment the counter for that word:
counts "word1" [("word1", 1), ("word2", 1)] => [("word1", 2), ("word2", 1)]
- Otherwise create a new count in the list:
counts "word3" [("word1", 1), ("word2", 1)] => [("word1", 1), ("word2", 1), ("word3", 1)]
Here is the code i have tried so far:
fun counts w [] [(w, 1)]
| counts w ((hd, n)::tl) =
if(w hd) then (hd, n+1)::tl
else if(not(w hd)) then [(hd, n)]@[(w, 1)]@tl
else (hd, n)::tl;
I am getting the right output for the second case, but for the first case this is the output i get:
counts "the" [("cat", 1), ("the", 1)];
val it = [("cat",1),("the",1),("the",1)] : (string * int) list