Operating on a return from a Maybe that contains “Just”

There are several solutions to your problem, all based around pattern matching. I’m assuming you have two algorithms (since you didn’t name them, I will):

algorithm1 :: a -> Maybe b
algorithm2 :: b -> c
input :: a

1) Pattern matching is typically done from either a case statement (below) or a function.

let val = algorithm1 input
in case val of
    Nothing -> defaultValue
    Just x  -> algorithm2 x

All other presented solutions use pattern matching, I’m just presenting standard functions that perform the pattern matching for you.

2) The prelude (and Data.Maybe) have some built-in functions to deal with Maybes. The maybe function is a great one, I suggest you use it. It’s defined in standard libraries as:

maybe :: c -> (b -> c) -> Maybe b -> c
maybe n _ Nothing  = n
maybe _ f (Just x) = f x

Your code would look like:

maybe defaultValue algorithm2 (algorithm1 input)

3) Since Maybe is a functor you could use fmap. This makes more sense if you don’t have a default value. The definition:

instance  Functor Maybe  where
    fmap _ Nothing       = Nothing
    fmap f (Just a)      = Just (f a)

So your code would look like:

fmap algorithm2 (algorithm1 input)

This output will be a Maybe value (Nothing if the result of algorithm1 is Nothing).

4) Finally, and strongly discouraged, is fromJust. Only use it if you are positive the first algorithm will return Just x (and not Nothing). Be careful! If you call fromJust val when val = Nothing then you get an exception, which is not appreciated in Haskell. Its definition:

fromJust          :: Maybe b -> b
fromJust Nothing  = error "Maybe.fromJust: Nothing" -- yuck
fromJust (Just x) = x

Leaving your code to look like:

algorithm2 (fromJust (algorithm1 input))

Leave a Comment