- Haskell Data Analysis Cookbook
- Nishant Shukla
- 221字
- 2021-12-08 12:43:36
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:
- We will use the
group
andsort
functions fromData.List
:import Data.List (group, sort)
- Define a simple data type for colors:
data Color = Red | Green | Blue deriving (Show, Ord, Eq)
- Create a list of these colors:
main :: IO () main = do let items = [Red, Green, Green, Blue, Red, Green, Green]
- 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.
推薦閱讀
- Visual C++程序設計學習筆記
- 程序員面試筆試寶典
- Animate CC二維動畫設計與制作(微課版)
- 琢石成器:Windows環境下32位匯編語言程序設計
- Ext JS 4 Web Application Development Cookbook
- Spring快速入門
- Python極簡講義:一本書入門數據分析與機器學習
- Getting Started with Eclipse Juno
- Citrix XenServer企業運維實戰
- Spring Boot+MVC實戰指南
- Orchestrating Docker
- PHP與MySQL權威指南
- JSP程序設計與案例實戰(慕課版)
- Vue.js光速入門及企業項目開發實戰
- C語言程序設計實驗指導與習題精解