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

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.

主站蜘蛛池模板: 孟津县| 岳普湖县| 屯昌县| 青阳县| 哈巴河县| 南通市| 泗洪县| 福州市| 晋中市| 保亭| 时尚| 昌平区| 尼木县| 西昌市| 潞西市| 尉犁县| 策勒县| 临清市| 肇东市| 房产| 芒康县| 明光市| 玛沁县| 济南市| 台南县| 普安县| 凤台县| 黄陵县| 句容市| 隆回县| 伊宁县| 赤峰市| 托里县| 柳河县| 平南县| 海原县| 鸡东县| 横峰县| 常宁市| 黄龙县| 建水县|