Having separated from the type of output, I would like to point out several alternative styles that you might prefer for writing such code:
First, you can case on multiple expressions by placing them in a tuple:
case (x,y) of (_ , Just 0) -> Nothing (Just x', Just y') -> Just (x' `div` y') _ -> Nothing
There are several ways to write this using security devices or even with the Control.Monad.guard function.
case (x,y) of (Just x', Just y') -> (x' `div` y') <$ guard (y' /= 0) _ -> Nothing
The second approach will start with the function:
safeDiv :: Integer -> Integer -> Maybe Integer safeDiv x 0 = Nothing safeDiv xy = Just (x `div` y)
Now that you have safeDiv , you can transfer it to Maybe-wrapped arguments. It is pretty close to Applicative style code, with the exception of the optional Maybe layer in the output. Fortunately, nested monads (e.g. Maybe (Maybe t) ) are trivial to crash:
maybe_divide xy = join $ safeDiv <$> x <*> y
or even
maybe_divide = (join .) . liftM2 safeDiv
if you are free to speak fluent.
Personally, I would use one of two variants of the tuple. But quite often it has a function like safeDiv , in which case the second form may be useful.
source share