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

Implementing a frequency table using Data.List

A frequency map of values is often useful to detect outliers. We can use it to identify frequencies that seem out of the ordinary. In this recipe, we will be counting the number of different colors in a list.

How to do it...

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

  1. We will use the group and sort functions from Data.List:
    import Data.List (group, sort)
  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 = 
         map (\x -> (head x, length x)) . group . sort $ items
      print freq

How it works...

Grouping identical items after sorting the list is the central idea.

See the following step-by-step evaluation in ghci:

Prelude> sort items

[Red,Red,Green,Green,Green,Green,Blue]
Prelude> group it

[[Red,Red],[Green,Green,Green,Green],[Blue]]

Prelude> map (\x -> (head x, length x)) it

[(Red,2),(Green,4),(Blue,1)]

Tip

As we may expect, sorting the list is the most expensive step.

See also

A cleaner version of the code is possible by using Data.MultiSet described in the next recipe, Implementing a frequency table using Data.MultiSet.

主站蜘蛛池模板: 建湖县| 金昌市| 双牌县| 阿瓦提县| 观塘区| 日土县| 酒泉市| 本溪| 吉木萨尔县| 双柏县| 聂拉木县| 株洲市| 尚志市| 永靖县| 内黄县| 满城县| 康定县| 正蓝旗| 嵩明县| 新巴尔虎右旗| 平阳县| 舟曲县| 舒兰市| 灌云县| 泸州市| 赤城县| 舒城县| 青神县| 双城市| 林州市| 思南县| 焉耆| 额敏县| 富顺县| 眉山市| 同德县| 报价| 乐亭县| 宁乡县| 望江县| 榆树市|