Book Image

Learning F# Functional Data Structures and Algorithms

By : Adnan Masood
Book Image

Learning F# Functional Data Structures and Algorithms

By: Adnan Masood

Overview of this book

Table of Contents (21 chapters)
Learning F# Functional Data Structures and Algorithms
Credits
Foreword
Foreword
Foreword
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Modeling graphs using F#


A graph can be modelled in multiple ways. For instance, we can simply represent it as a collection of vertices and edges. Alternatively, it can be defined as a set of tuples containing a vertex and a set of corresponding edges. In either approach, we have to consider space-time trade-off. For example, in order to effectively represent a graph where paths can be determined quickly, we can build a data structure, which encapsulates the set of vertices and edges. However, this will result in an exponential growth of the space proportional to the square of the number of vertices.

Now, we will show one approach to model a graph in F#. The individual constructs defined here, as well as the complete code listing, can be found in the source code of the book at http://www.packtpub.com/support. In our representation, a graph consists of nodes and edges, as shown in the following code snippet:

type Graph() = 
  let mutable nodes = []
  let mutable edges = []
  member this.Nodes...