Coping with unexpected or missing input
Data sources often contain incomplete and unexpected data. One common approach to parsing such data in Haskell is using the Maybe
data type.
Imagine designing a function to find the nth element in a list of characters. A naïve implementation may have the type Int -> [Char] -> Char
. However, if the function is trying to access an index out of bounds, we should try to indicate that an error has occurred.
A common way to deal with these errors is by encapsulating the output Char
into a Maybe
context. Having the type Int -> [Char] -> Maybe Char
allows for some better error handling. The constructors for Maybe
are Just a
or Nothing
, which will become apparent by running GHCi and testing out the following commands:
$ ghci Prelude> :type Just 'c' Just 'c' :: Maybe Char Prelude> :type Nothing Nothing :: Maybe a
We will set each field as a Maybe
data type so that whenever a field cannot be parsed, it will simply be...