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

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.

主站蜘蛛池模板: 安阳县| 大化| 巩义市| 罗山县| 石城县| 左贡县| 桂平市| 建平县| 虹口区| 周宁县| 临安市| 农安县| 长子县| 淳化县| 灵石县| 绩溪县| 太谷县| 得荣县| 永胜县| 沙湾县| 额敏县| 上思县| 芜湖市| 敦化市| 四子王旗| 遂昌县| 刚察县| 内江市| 巴林左旗| 清水河县| 武义县| 杭锦旗| 建昌县| 宁城县| 当阳市| 隆子县| 尉犁县| 平凉市| 拜泉县| 昌乐县| 玛曲县|