Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

haskell - 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 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...