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

∥☆過路亽.° 提交于 2019-11-26 08:51:51
Thomas M. DuBuisson

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))

You're looking for fromJust. But only if you're certain your Maybe function is not going to return a Nothing!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!