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

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.

主站蜘蛛池模板: 潜山县| 潮安县| 油尖旺区| 闵行区| 屯门区| 上杭县| 云林县| 永康市| 康乐县| 上虞市| 达孜县| 鄂伦春自治旗| 沧州市| 荆门市| 定州市| 汝阳县| 景宁| 成武县| 永寿县| 阳泉市| 明光市| 潜山县| 华亭县| 津南区| 额尔古纳市| 普兰店市| 临城县| 航空| 迁西县| 边坝县| 施甸县| 澄江县| 犍为县| 祁东县| 宁化县| 呼伦贝尔市| 奉贤区| 沭阳县| 垣曲县| 永昌县| 临湘市|