[Haskell-beginners] Handling Maybes
Elvio Toccalino
elviotoccalino at gmail.com
Wed May 25 05:21:51 CEST 2011
Your second option may or may not be dangerous, but it sure looks
tricky. I wouldn't use 'maybe' that way.
How about this?
main = do val <- someIOFunc -- val is a Maybe String
maybe (someAction >> someOtherActionEtc)
(\theValue -> putStrLn ("the string in reverse is " ++
(reverse theValue))
val
If you like point-free definitions:
main = do val <- someIOFunc -- val is a Maybe String
maybe (someAction >> someOtherActionEtc)
(putStrLn . ("the string in reverse is " ++) . reverse)
val
The difference is that my use of 'maybe' involves giving it actions, and
not just pure functions.
On Tue, 2011-05-24 at 19:09 -0800, 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?
>
More information about the Beginners
mailing list