开发者

Operating on a return from a Maybe that contains "Just"

I have a function that has a return type of Maybe ([(Int,Int)],(Int,Int))

I would like to call this from another function and perform an operation on the data.

However, the return value is contained within Just. The second method takes ([(Int,Int)],(Int,Int)) and therefore will not accept Just ([(Int,Int)],(Int,Int)).

Is there a way I can trim the Just before applying the开发者_JAVA技巧 second method?

I don't fully understand the use of Just within Maybe - however, I have been told that the return type for the first Method must be Maybe.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜