Using Maybe
Maybe
is a sum type very often used to indicate a NULL
value or nothing. In fact, it is a very type-safe way of representing a NULL
value. Explicitly saying that we have either a value or nothing makes our life simpler during programming steps, which can fail, and we may not want to continue.
In this recipe, you will learn to use the Maybe
data type.
Getting ready
Create a new project called using-maybe
using the simple
stack template. Change into the directory and build the solution:
stack new using-maybe simple stack build
How to do it...
- Open
src/Main.hs
. We will experiment in themain
function in this file. Replace themain
function with following content:
main :: IO () main = do putStrLn "Using Maybe"
- Continue in the same function. Start defining various values of
Maybe
.Maybe
is a sum type that may contain a value. The data constructorJust
takes the value, whereas the constructorNothing
represents the absence of any value. Define three instances...