0

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
madcrazydrumma
  • 1,847
  • 3
  • 20
  • 38

1 Answers1

1

According to the details mentioned by you, this should work:

fun count w [] = [(w, 1)]
| count w ((w', c)::tl) = 
    if w = w'
    then (w', c+1)::tl
    else (w', c)::(count w tl);

count "the" [("cat", 1), ("the", 1)];
count "word1" [("word1", 1), ("word2", 1)];
count "word2" [("word1", 1), ("word2", 1)];
count "word1" [];
count "word1" [("word1", 1)];
Kevin Johnson
  • 1,890
  • 13
  • 15