Book Image

Haskell Data Analysis cookbook

By : Nishant Shukla
Book Image

Haskell Data Analysis cookbook

By: Nishant Shukla

Overview of this book

Step-by-step recipes filled with practical code samples and engaging examples demonstrate Haskell in practice, and then the concepts behind the code. This book shows functional developers and analysts how to leverage their existing knowledge of Haskell specifically for high-quality data analysis. A good understanding of data sets and functional programming is assumed.
Table of Contents (14 chapters)
13
Index

Exporting data as JSON

A convenient way to store data that may not adhere to a strict schema is through JSON. To accomplish this, we will use a painless JSON library called Yocto. It sacrifices performance for readability and small size.

In this recipe, we will export a list of points as JSON.

Getting ready

Install the Yocto JSON encoder and decoder from cabal using the following command:

$ cabal install yocto

How to do it…

Start by creating a new file, which we call Main.hs and perform the following steps:

  1. Import the relevant data structures, as shown in the following code:
    import Text.JSON.Yocto
    import qualified Data.Map as M
  2. Define a data structure for 2D points:
    data Point = Point Rational Rational
  3. Convert a Point data type into a JSON object, as shown in the following code:
    pointObject (Point x y) = 
      Object $ M.fromList [ ("x", Number x)
                          , ("y", Number y)]
  4. Create the points and construct a JSON array out of them:
    main = do
      let points = [ Point...