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 buildHow to do it...
- Open
src/Main.hs. We will experiment in themainfunction in this file. Replace themainfunction with following content:
main :: IO ()
main = do
putStrLn "Using Maybe"- Continue in the same function. Start defining various values of
Maybe.Maybeis a sum type that may contain a value. The data constructorJusttakes the value, whereas the constructorNothingrepresents the absence of any value. Define three instances...