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

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