O'Reilly logo

Haskell Cookbook by Yogesh Sajanikar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Open src/Main.hs; we will be using this file for our recipe.
  2. Define a binary tree data type:
        data BinaryTree a = Leaf          | BinaryTree { left :: BinaryTree a                               , val :: a                               , right :: BinaryTree a }          deriving Show
  1. Write the helper functions empty, singleton, and node to create an empty tree and a tree with a single node, and compose the two trees with a value to create a new tree:
        empty :: BinaryTree a        empty = Leaf       singleton :: a -> BinaryTree a       singleton x = BinaryTree Leaf x Leaf       node :: BinaryTree a -> a -> BinaryTree a -> BinaryTree a       node l x r = BinaryTree { left = l, val = x, right = r }
  1. Define in-order depth first traversal for the binary tree:
        dfTraverse :: BinaryTree a -> [a]        dfTraverse Leaf = [] dfTraverse tree ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required