Working with monad
In this recipe, we will define our own Maybe type. We will define the Functor and Applicative instances for our Maybe, which are prerequisites for creating a Monad instance. Then, we will continue to create an instance of Monad, and, finally, we will use them in an example.
Maybe is a simple type and its monad instance is simple to implement and understand. Hence, when we work with the Maybe monad, it becomes clearer why and how the monad works.
How to do it...
- Create a new project
working-with-monadusing thesimpleStack template:
stack new working-with-monad simple
- Open
src/Main.hsand edit it.
- After the initial module definition, add the following imports:
import Prelude hiding(Maybe(..))
Note
Note that we are importing otherwise implicitly imported module Prelude explicitly by hiding Maybe. This is because we are defining our own Maybe data type.
- Import other required headers now. The header for monad is
Control.Monad:
import Data.Functor
import...