Haskell Card Amount

Is there a standard function for summing all the values ​​on a Haskell map. Does my card read something like [(a, 2), (b, 4), (c, 6)]?

Essentially, I'm trying to make this a normalized frequency distribution. Thus, the key values ​​on the given map are considered the values ​​a, b, c. I need to normalize them as [(a, 1/6), (b, 1/3), (c, 1/2)]

+5
source share
3 answers

You can simply do Map.foldl' (+) 0(or M.foldl'if you imported Data.Map as M).

foldl' (+) 0 . Map.elems, . ( apostrophe - foldl foldr, (Int, Integer, Float, Double ..), , , , .)

containers ( >= 0.4.2.0) Data.Map.foldl ', cabal install, GHC. , GHC 7.2 , foldl' (+) 0 . Map.elems - .

Data.Foldable.sum, Foldable typeclass, - .

:

normalize :: (Fractional a) => Map k a -> Map k a
normalize m = Map.map (/ total) m
  where total = foldl' (+) 0 $ Map.elems m

Data.List foldl'.

+4
let
    total = foldr (\(_, n) r -> r + n) 0 l
in map (\(x, y) -> (x, y/total) l

l - .

+3

Plain:

import qualified Data.Map as M

sumMap = M.foldl' (+) 0

normalizeMap m =
  let s = sumMap m in
    M.map (/ s) m

main = do
  let m = M.fromList [("foo", 1), ("bar", 2), ("baz", 6)]
  (print . sumMap) m
  (print . normalizeMap) m

prints:

9.0
fromList [("bar",0.2222222222222222),("baz",0.6666666666666666),("foo",0.1111111111111111)]
+3
source

All Articles