Binary tree as Functor
In the last recipe, we have Functor
instances defined for Maybe
, Either
, and List
. We even defined the Functor
instance. In this recipe, we will create a data type Binary Tree
and define a Functor
instance for it.
How to do it...
- Create a new Haskell project
binary-tree-functor
using thesimple
Stack template:
stack new binary-tree-functor simple
- Open
src/Main.hs
. This is the file that will be used for our purposes. - After adding module definition for
Main
, add the following import:
module Main where import Data.Functor
- Define the
binary tree
andutility
functions to create thetree
:
-- The tree can be empty (Leaf) or a node with a -- value, left and right trees. data Tree a = Leaf | Node (Tree a) a (Tree a) deriving (Show, Eq)
-- Create a tree given a value, left tree and a right tree node :: Tree a -> a -> Tree a -> Tree a node l x r = Node l x r
-- Induct a value...