Binary tree as Applicative
In this example, we will define binary tree
and define it as an instance of an Applicative
type class.
How to do it...
- Create a new project
binary-tree-applicative
using thesimple
Stack template. - Open
src/Main.hs
; we will add our recipe to this file. - After the initial module definition, add the following imports:
module Main where import Data.Functor import Control.Applicative
- Define the
binary tree
and add theFunctor
instance too:
data Tree a = Leaf | Node (Tree a) a (Tree a) deriving (Show, Eq) instance Functor Tree where fmap _ Leaf = Leaf fmap f (Node left value right) = Node (fmap f left) (f value) (fmap f right)
- Now, define the
Applicative
instance for thebinary tree
. Note the recursive definition forpure
, producing an infinite tree:
instance Applicative Tree where pure x = let t = Node t x t in t (<*>) Leaf _ = Leaf (<...