Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Prelude Hack : divide and remainder return Either Monad

More than 5 years have passed since last update.

See also
1. http://voqn.blogspot.com/2012/01/bdd-on-haskell-3-1-catch.html
2. http://voqn.blogspot.com/2012/01/bdd-on-haskell-3-2-throw-exception.html

import qualified Data.Fixed as F
import Control.Exception
import Prelude hiding ( div, mod, divMod )
import qualified GHC.Real as R

divZero :: Either ArithException a
divZero = Left DivideByZero

div' :: (Real a, Integral b) => a -> a -> Either ArithException b
div' _ 0 = divZero
div' x y = Right $ F.div' x y

mod' :: Real a => a -> a -> Either ArithException a
mod' _ 0 = divZero
mod' x y = Right $ F.mod' x y

divMod' :: (Real a, Integral b) => a -> a -> Either ArithException (b, a)
divMod' = pairEither div' mod' divZero

div :: Integral a => a -> a -> Either ArithException a
div _ 0 = divZero
div x y = Right $ R.div x y

mod :: Integral a => a -> a -> Either ArithException a
mod _ 0 = divZero
mod x y = Right $ R.mod x y

divMod :: Integral a => a -> a -> Either ArithException (a, a)
divMod = pairEither div mod divZero

pairEither f g e x y = case (f x y, g x y) of
  (Right n, Right m) -> Right (n, m)
  _ -> e
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away