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

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.

主站蜘蛛池模板: 东海县| 东兰县| 酉阳| 宝兴县| 城市| 德化县| 西城区| 丽水市| 自治县| 耿马| 巢湖市| 广汉市| 庆阳市| 宜川县| 琼中| 宁强县| 堆龙德庆县| 乐平市| 永安市| 县级市| 彭山县| 古丈县| 云阳县| 防城港市| 木里| 钦州市| 德州市| 井陉县| 江达县| 唐河县| 土默特右旗| 麻阳| 炉霍县| 义马市| 孟州市| 临江市| 呼图壁县| 西昌市| 大兴区| 高要市| 海城市|