CodeAbbey #21 Array Counters I'm trying to learn some Haskell by working my way through the CodeAbbey problems. I really struggled to find a nice functional (but still efficient) way to solve problem #21: Array Counters.

The problem is, given a list of M numbers between 1 and N (an input parameter), to count the number of occurrences of each number. The question strongly suggests the imperative approach of using an array of counters and incrementing the counter at the relevant index.

Example:

Input:
10 3
3 2 1 2 3 1 1 1 1 3

Expected output:
5 2 3


My code:

count :: Int -&gt; [Int] -&gt; [Int]
count n = go (replicate n 0)
  where
    go cs []       = cs
    go cs (x : xs) = go (incList x cs) xs

incList :: Int -&gt; [Int] -&gt; [Int]
incList x cs = (take (x - 1) cs) ++ [cs!!(x - 1) + 1] ++ (drop x cs)

main :: IO ()
main = do line &lt;- getLine
          let [m, n] = map (read :: String -&gt; Int) $ words line
          line &lt;- getLine
          let list = map (read :: String -&gt; Int) $ words line
          putStrLn $ unwords $ map show $ count n list
You could use a Map, from the Data.Map module to count occurrences of the numbers:

import qualified Data.Map.Strict as M

count :: [Int] -&gt; M.Map Int Int
count xs = M.fromListWith (+) $ zip xs (repeat 1)


This way you only iterate once through the list of pairs (number, 1) and sum the 1s of each different number.

Since we don't have mutation in Haskell, you can often use a Map as a replacement for a dictionary in imperative languages (or arrays).