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 (19 chapters)
Haskell Data Analysis Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Defining a binary tree data type


In a binary tree, each node has at most two children. We will define a data structure to encompass the left and right subtrees of each node.

Getting ready

The code in the recipe will represent the following tree. The root node is labeled n3 with a value of 3. It has a left node n1 of value 1, and a right node n2 of value 2.

How to do it...

  1. This code requires no imports. We can jump in and define the data structure recursively. A tree can either be a node with values or null/empty:

    data Tree a = Node { value	:: a
                       , left  :: (Tree a)
                       , right:: (Tree a) }
                | Leaf 
                deriving Show
  2. In main, create the tree shown in the preceding diagram and print it out:

    main = do
      let n1 = Node { value = 1, left = Leaf, right = Leaf }
      let n2 = Node { value = 2, left = Leaf, right = Leaf }
      let n3 = Node { value = 3, left = n1,   right = n2 }
      print n3
  3. The full tree is printed out as follows:

    $ runhaskell Main.hs
    
    Node {...