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. Create a new project binary-tree-applicative using the simple Stack template.
  2. Open src/Main.hs; we will add our recipe to this file.
  3. After the initial module definition, add the following imports:
        module Main where

        import Data.Functor
        import Control.Applicative
  1. Define the binary tree and add the Functor 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)
  1. Now, define the Applicative instance for the binary tree. Note the recursive definition for pure, producing an infinite tree:
        instance Applicative Tree where        pure x = let t = Node t x t
           in t (<*>) Leaf _ = Leaf (<*>) ...

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