Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can simply do <code>Map.foldl' (+) 0</code> (or <code>M.foldl'</code>, if you imported Data.Map as <code>M</code>).</p> <p>This is just like <code>foldl' (+) 0 . Map.elems</code>, but slightly more efficient. (Don't forget the apostrophe — using foldl or foldr to do sums with the standard numeric types (Int, Integer, Float, Double, etc.) will build up huge thunks, which will use up lots of memory and possibly cause your program to overflow the stack.)</p> <p>However, only sufficiently recent versions of <a href="http://hackage.haskell.org/package/containers" rel="nofollow">containers</a> (>= 0.4.2.0) contain <a href="http://hackage.haskell.org/packages/archive/containers/0.4.2.0/doc/html/Data-Map.html#v%3afoldl-39-" rel="nofollow">Data.Map.foldl'</a>, and you shouldn't upgrade it with <code>cabal install</code>, since it comes with GHC. So unless you're on GHC 7.2 or above, <code>foldl' (+) 0 . Map.elems</code> is the best way to accomplish this.</p> <p>You could also use <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Foldable.html#v%3asum" rel="nofollow">Data.Foldable.sum</a>, which works on any instance of the <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Foldable.html#t%3aFoldable" rel="nofollow">Foldable</a> typeclass, but will still build up large thunks on the common numeric types.</p> <p>Here's a complete example:</p> <pre><code>normalize :: (Fractional a) =&gt; Map k a -&gt; Map k a normalize m = Map.map (/ total) m where total = foldl' (+) 0 $ Map.elems m </code></pre> <p>You'll need to import Data.List to use <code>foldl'</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload