1

I'm trying to compile this piece of code but it doesn't work and I don't get it:

division :: Maybe Int -> Maybe Int -> Maybe Int
division _ (Maybe 0) = Nothing
division (Maybe a) (Maybe b) = Just (a `div` b)
6
  • 1
    Maybe Maybe is not a constructor of Maybe a Commented Aug 7, 2017 at 18:16
  • i meant that the function take two parameters of type MAybe and return a maybe value. any corrections? Commented Aug 7, 2017 at 18:24
  • yes, but in the body of the function, you can not use (Maybe 0), etc. Then you have to pick a constructor, like Just 0, not Maybe 0. Commented Aug 7, 2017 at 18:25
  • 1
    As a style thing: I recommend leaving the arguments as bare Ints rather than Maybe Ints, as in division :: Int -> Int -> Maybe Int; division _ 0 = Nothing; division a b = a `div` b. If you need the arguments to be Maybes, then you can use do notation; if ma :: Maybe Int and mb :: Maybe Int, then do a <- ma; b <- mb; division a b is well-typed. Commented Aug 7, 2017 at 18:58
  • @DanielWagner You're missing a Just in division a b = a `div` b. Commented Aug 8, 2017 at 10:15

2 Answers 2

2

Maybe a is defined as:

data Maybe a = Just a | Nothing

so you can not put Maybe a in the function defintion, only in the signature:

division :: Maybe Int -> Maybe Int -> Maybe Int
division _ (Just 0) = Nothing
division (Just a) (Just b) = Just (a `div` b)

Furthermore the function is not total: not every possible case of input is handled by the function, so this could result in an exception. So you better return something in those cases (usually one returns Nothing):

division :: Maybe Int -> Maybe Int -> Maybe Int
division _ (Just 0) = Nothing
division (Just a) (Just b) = Just (a `div` b)
division _ _ = Nothing

Finally we can use Integral i as type, instead of Int and make the function more generic:

division :: Integral i => Maybe i -> Maybe i -> Maybe i
division _ (Just 0) = Nothing
division (Just a) (Just b) = Just (a `div` b)
division _ _ = Nothing
Sign up to request clarification or add additional context in comments.

Comments

1

Based on Daniel Wagner's comment and Willem Van Onsem's point about Integral, this is how I would write the function:

division :: Integral a => a -> a -> Maybe a
division _ 0 = Nothing
division p q = Just (div p q)

To use it with Maybe arguments, you can simply write

division <$> m <*> n

or, equivalently,

liftA2 division m n

where liftA2 is in Control.Applicative.

Comments

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.