Book Image

Haskell Cookbook

Book Image

Haskell Cookbook

Overview of this book

Haskell is a purely functional language that has the great ability to develop large and difficult, but easily maintainable software. Haskell Cookbook provides recipes that start by illustrating the principles of functional programming in Haskell, and then gradually build up your expertise in creating industrial-strength programs to accomplish any goal. The book covers topics such as Functors, Applicatives, Monads, and Transformers. You will learn various ways to handle state in your application and explore advanced topics such as Generalized Algebraic Data Types, higher kind types, existential types, and type families. The book will discuss the association of lenses with type classes such as Functor, Foldable, and Traversable to help you manage deep data structures. With the help of the wide selection of examples in this book, you will be able to upgrade your Haskell programming skills and develop scalable software idiomatically.
Table of Contents (13 chapters)

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...

  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) 
...