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

Navigating the tree


Consider the tree in the following figure. Our objective is to traverse the tree, that is, iterate through the nodes. There are several different approaches to do so but some of the most common ones are in-order, post-order, and pre-order traversal:

In the in-order traversal, we start from the root node and traverse to left subtree, and then we visit the root node and then traverse to right subtree as seen in the following. The nodes are traversed in this order: A, B, C, D, …, H, I:

An in-order traversal algorithm can be implemented in F# as the following recursive function. In this function, we utilize the power of sequences, and the match expressions to implement the in-order traversal algorithm:

type Tree<'a> =
  | Tree of 'a * Tree<'a> * Tree<'a>
  | Leaf of 'a

let rec inorder tree =
  seq {
    match tree with
      | Tree(x, left, right) ->
      yield! inorder left
      yield x
      yield! inorder right
   | Leaf x -> yield x
  }

As you have...