[Haskell-beginners] Handling Maybes

Erik de Castro Lopo mle+hs at mega-nerd.com
Wed May 25 05:15:58 CEST 2011


Christopher Howard wrote:

> Since I started into Haskell, I frequently run into a scenario like
> this: some function returns a Maybe value. If it is a Nothing, I want to
> do one thing, but if it isn't, I want to do something with the value
> encapsulated by the Maybe. But before I can use that value (say, to
> print it) I've got to pull it out of the Maybe in a way that satisfies
> the compiler. So one option is to use a separate function with pattern
> matching, for example:
> 
> handleMaybeVal Nothing = do someAction
>                             someOtherActionEtc
> handleMaybeVal (Just a) = putStrLn ("The string in reverse is " ++
>                                    (reverse a))
> 
> Or I can use the maybe function with a conditional
> 
> main = do val <- someIOFunc -- val is a Maybe String
>           if val == Nothing
>             then do someAction
>               someOtherActionEtc
>             else putStrLn ("The string in reverse is " ++
>                           ((reverse . unpack) val))
>   where unpack a = maybe
>                      (error "unreachable error")
>                      (\b -> b) a
> 
> The second option I like better, for some reason, but it is a bit
> dangerous, as I have to double check my code to make sure the default
> value passed to "maybe" cannot possibly be evaluated. (Alternatively, I
> could pass in a regular default value, like a blank string, though that
> is actually more dangerous in my mind because a bad value might be used
> silently.)
> 
> Anyway: how do you pros go about handling situations like these?

I usually prefer an explicit pattern match like this:

main = do val <- someIOFunc -- val is a Maybe String
          case val of
            Nothing -> do someAction
                          someOtherActionEtc
            Just s  -> putStrLn ("The string in reverse is " ++ (reverse s))


HTH,
Erik
-- 
----------------------------------------------------------------------
Erik de Castro Lopo
http://www.mega-nerd.com/



More information about the Beginners mailing list