官术网_书友最值得收藏!

Implementing a frequency table using Data.MultiSet

A frequency map of values is often useful to detect outliers. We will use an existing library that does much of the work for us.

Getting ready

We will be using the multiset package from Hackage:

$ cabal install multiset

How to do it...

Create a new file, which we will call Main.hs, and perform the following steps:

  1. We will use the fromList and toOccurList functions from Data.MultiSet:
    import Data.MultiSet (fromList, toOccurList)
  2. Define a simple data type for colors:
    data Color = Red | Green | Blue deriving (Show, Ord, Eq)
  3. Create a list of these colors:
    main :: IO ()
    main = do
      let items = [Red, Green, Green, Blue, Red, Green, Green]
  4. Implement the frequency map and print it out:
      let freq = toOccurList . fromList $ items
      print freq
  5. Run the code to display the frequency list:
    $ runhaskell Main.hs
    
    [ (Red, 2), (Green, 4), (Blue, 1) ]
    

How it works...

The toOccurList :: MultiSet a -> [(a, Int)] function creates a frequency map from a list. We construct MuliSet using the provided fromList function.

See also

If importing a new library is not desired, see the previous recipe on Implementing a frequency map using Data.List.

主站蜘蛛池模板: 会东县| 洪江市| 新巴尔虎左旗| 嘉义县| 汉阴县| 格尔木市| 从江县| 礼泉县| 柞水县| 静安区| 区。| 乌兰浩特市| 开鲁县| 镇江市| 拉孜县| 厦门市| 布尔津县| 华亭县| 合肥市| 枣阳市| 酒泉市| 河北区| 武宁县| 汨罗市| 甘洛县| 民丰县| 高阳县| 清徐县| 舒兰市| 宁波市| 化德县| 隆德县| 肇州县| 吉林市| 宜君县| 合作市| 陆良县| 砚山县| 营山县| 平顶山市| 蓬莱市|