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

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.

主站蜘蛛池模板: 福清市| 那曲县| 天峨县| 长垣县| 海兴县| 桑植县| 英德市| 永昌县| 滦平县| 闸北区| 梁山县| 新干县| 惠来县| 尼木县| 旬邑县| 囊谦县| 涞源县| 满洲里市| 色达县| 固安县| 襄汾县| 阳新县| 济南市| 绍兴县| 东丰县| 衡水市| 芒康县| 诏安县| 康保县| 高要市| 黄梅县| 顺义区| 泸西县| 巴东县| 麻阳| 永平县| 普兰店市| 长沙市| 阳高县| 娱乐| 邵武市|