增加单词和计数器列表中单词的计数器
Incrementing a counter for a word in a list of words and counters
所以我有一个单词和计数器的列表:
[("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
根据你提到的细节,这应该有效:
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)];
所以我有一个单词和计数器的列表:
[("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
根据你提到的细节,这应该有效:
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)];