1

I'm still a beginner in Haskell.

My code

secureDivide :: Int -> Int -> Maybe Int
secureDivide _ 0 = Nothing
secureDivide 0 _ = Nothing
secureDivide x y = Just (x `div` y)

addOne:: Maybe Int -> Maybe Int
addOne (Just n) = Just (n + 1)

Actually I don't have any problem and get the result I want with 'secureDivide'.

Example : secureDivide 10 0 -> Nothing

But when I try something like this :

mySecureNext (mySecureDiv 10 0) -> I have an 'Exception' and not 'Nothing'

Is there a way to handle an error to a message without import something with the if-else statement like if error = Nothing else Just ... (or other option) ?

5
  • 3
    you need to handle the Nothing case in your addOne function. A better pattern is to simply define your addOne function as Int -> Maybe Int. Then you can utilize the fact that Maybe is a monad and do secureDivide >>= addOne Commented Sep 8, 2022 at 14:58
  • Does this answer your question? Maybe monad usage example Commented Sep 8, 2022 at 15:01
  • 3
    Is mySecureNext supposed to be addOne? Commented Sep 8, 2022 at 15:11
  • 4
    addOne = fmap (+1). The definition of fmap takes care of both Just arguments and Nothing arguments. Your current definition duplicates the Just logic while ignoring the Nothing logic. Commented Sep 8, 2022 at 15:12
  • 4
    Also, you can drop secureDivide 0 _ = Nothing. There is no problem dividing 0 by a nonzero value, so it doesn't need to be caught and handled separately. (If you do handle it separately, the result should be Just 0, not Nothing.) Commented Sep 8, 2022 at 15:13

1 Answer 1

3

In Data.Maybe there is function

maybe :: b -> (a -> b) -> Maybe a -> b

Examples of use

maybe 0 (+1) Nothing
> 0
maybe 0 (+1) (Just 10)
> 11

About addOne

a) You can add alternative variant of execution

addOne :: Maybe Int -> Maybe Int
addOne (Just n) = Just (n + 1)
addOne Nothing = Nothing

addOne (mySecureDiv 10 0)

b) You can change function to monadic function

addOne :: Int -> Maybe Int
addOne n = Just (n + 1)

And compose functions by

-- (>>=) :: m a -> (a -> m b) -> m b
-- or specific version
-- (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b

(mySecureDiv 10 0) >>= addOne

c) You can make pure function

addOne :: Int -> Int
addOne n = n + 1

And compose functions by

-- fmap :: (a -> b) -> f a -> f b
-- or specific version
-- fmap :: (a -> b) -> Maybe a -> Maybe b
-- or infix version <$>

fmap addOne (mySecureDiv 10 0)
addOne <$> (mySecureDiv 10 0)
Sign up to request clarification or add additional context in comments.

1 Comment

The multiple ways to solve with a monad or with compose is super helpful. This really "clicked" in my brain. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.