holmen
holmen

Reputation: 75

How to sum values in F# Map collection

I have a Map<string,int> where I want to sum all values.

It will be used as word dictionary in a toy spelling corrector which is described here.

Naive attempt

let wc myMap =
    Map.toSeq myMap
    |> Seq.sumBy (fun kvp -> (snd kvp))

error FS0071 Consider adding further type constraints

Attempt 1

type MapFn = Map<string,int> -> int
let wc:MapFn = (function wm ->
                            Map.toSeq wm
                            |> Seq.sumBy (fun kvp -> (snd kvp)))

Attempt 2

type WordMap = WordMap of Map<string,int>
let wc (WordMap wm) = 
    Map.toSeq wm
    |> Seq.sumBy (fun kvp -> (snd kvp))

Both attempts work, however I would like code tidier. Like sample code in Python sum(WORDS.values()).

WORDS = Counter(words(open('big.txt').read()))

def P(word, N=sum(WORDS.values())): 
    return WORDS[word] / N

Also wonder if type Map<string,int> is the best choice for my dictionary.

Upvotes: 2

Views: 742

Answers (1)

Branimir
Branimir

Reputation: 4367

Map element is a key/value pair (KeyValuePair<string, int> in your example), not a tuple. So you should use kvp.Value instead of snd kvp, for example:

myMap |> Seq.sumBy(fun item -> item.Value )

or using Map.fold

myMap |> Map.fold (fun state key value -> state + value)  0

Upvotes: 2

Related Questions