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

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.

主站蜘蛛池模板: 明溪县| 平安县| 东台市| 茶陵县| 青阳县| 万全县| 长葛市| 宝山区| 河北省| 枣阳市| 黑龙江省| 石景山区| 盐亭县| 无极县| 富平县| 汝州市| 包头市| 隆安县| 涿州市| 虹口区| 泰安市| 东丽区| 万载县| 益阳市| 墨竹工卡县| 襄城县| 孟州市| 平利县| 呼图壁县| 三门县| 黄梅县| 武陟县| 广饶县| 厦门市| 肃北| 承德市| 常熟市| 中阳县| 抚宁县| 百色市| 屏南县|