[Haskell-beginners] Handling Maybes
Christopher Howard
christopher.howard at frigidcode.com
Wed May 25 05:09:05 CEST 2011
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?
--
frigidcode.com
theologia.indicium.us
More information about the Beginners
mailing list