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

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.

主站蜘蛛池模板: 天长市| 察隅县| 太谷县| 阿图什市| 东乡县| 宿州市| 新疆| 汕头市| 漳浦县| 肥乡县| 镇康县| 池州市| 滦南县| 永川市| 庆安县| 白水县| 扬州市| 玛沁县| 阜南县| 东莞市| 汤原县| 江津市| 玛多县| 河间市| 夏河县| 金寨县| 安达市| 兴国县| 云安县| 阳山县| 全州县| 甘洛县| 乌苏市| 红桥区| 嘉善县| 福清市| 长治县| 宁城县| 镶黄旗| 安岳县| 增城市|