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

Representing a graph from a list of edges


A graph can be defined by a list of edges, where an edge is a tuple of vertices. In the Data.Graph package, a vertex is simply Int. In this recipe, we use the buildG function to construct a graph data structure out of a list of edges.

Getting ready

We will be constructing the graph represented in the following diagram:

How to do it...

Create a new file, which we will name Main.hs, and insert the following code:

  1. Import the Data.Graph package:

    import Data.Graph
  2. Construct a graph using the buildG function from the imported library:

    myGraph :: Graph
    
    myGraph= buildG bounds edges  
      where  bounds = (1,4)
          edges = [ (1,3), (1,4)
                  , (2,3), (2,4) 
                  , (3,4) ]
  3. Print out the graph, its edges, and its vertices:

    main = do
      print $ "The edges are " ++ (show.edges) myGraph
      print $ "The vertices are " ++ (show.vertices) myGraph

How it works...

A list of edges is fed to the buildG :: Bounds -> [Edge] -> Graph function to form a graph...