How can I handle an error from another function in Haskell?

Viewed 74

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

1 Answers

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