Book Image

Haskell Data Analysis Cookbook

By : Nishant Shukla
Book Image

Haskell Data Analysis Cookbook

By: Nishant Shukla

Overview of this book

Table of Contents (19 chapters)
Haskell Data Analysis Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...