The idea is that a function might fail. Let's say the functions job is to find an element in a list that meets some requirment. Perhaps to find an odd integer. But the list is finite and there is no odd integer. So we let our "finder" function return a Maybe type. The return value is one of:
Nothing Just 111If you want to write a function that returns a Maybe, you do something like this:
checkval x = if ( x < 100 )
then
Just x
else
Nothing
The concept is very simple, but we then face a variety of challenges
dealing with a result of this type. One way to unwrap that 111 value
that is encapsulated in the Maybe type would be a function like this.
showmb Nothing = "sorry" showmb (Just x) = "The value is: " ++ show xHere the "showmb" function (my shorthand name for showMaybe) uses pattern matching on the argument to convert the Maybe to a string. If the argument is Nothing we get the string "sorry". If not, we fall through to the next line. Here pattern matching does the work of parsing away the Just. We have to surround it with parethesis because there is just a single argument. We then use "show" to convert whatever is extracted into a string.
main = putStrLn $ showmb $ checkval 45 The value is: 45And we get the result shown.
I ran into a Maybe type early in my Haskell journey and was frustrated. The only way I knew how to deal with it was pattern matching like the above. I suspected there was a better way. And there is, by using functors, applicatives, and monads to perform calculations on values inside of containers like Maybe. In fact that really is the purpose of those typeclasses.
Tom's software pages / tom@mmto.org