增加单词和计数器列表中单词的计数器

时间:2015-10-25 18:12:46

标签: sml smlnj

所以我有一个单词和计数器列表:

[("word1", 1), ("word2", 1)]

我想知道如何为我添加到该列表中的单词递增计数器,例如:

  • 如果单词已在列表中,请递增该单词的计数器:
    • counts "word1" [("word1", 1), ("word2", 1)] => [("word1", 2), ("word2", 1)]
  • 否则在列表中创建一个新计数:
    • counts "word3" [("word1", 1), ("word2", 1)] => [("word1", 1), ("word2", 1), ("word3", 1)]

这是我到目前为止尝试过的代码:

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;

我得到第二种情况的正确输出,但对于第一种情况,这是我得到的输出:

counts "the" [("cat", 1), ("the", 1)];
val it = [("cat",1),("the",1),("the",1)] : (string * int) list

1 个答案:

答案 0 :(得分:1)

根据你提到的细节,这应该有效:

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)];