Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {-# LANGUAGE FlexibleInstances #-}
- {-# LANGUAGE MultiParamTypeClasses #-}
- {-# LANGUAGE FlexibleContexts #-}
- import Control.Monad.Error
- import Control.Applicative
- data Excep a = Err String | Ok a
- deriving (Eq, Show)
- instance Monad Excep where
- return = Ok
- Ok a >>= f = f a
- Err a >>= _ = Err a
- instance Applicative Excep where
- pure = return
- (<*>) = ap
- instance Functor Excep where
- fmap = liftM
- instance Alternative Excep where
- (<|>) = mplus
- empty = mzero
- instance MonadPlus Excep where
- mzero = Err "MonadPlus.mzero error."
- Err _ `mplus` _ = Err "MonadPlus.mzero error."
- _ `mplus` Err _ = Err "MonadPlus.mzero error."
- Ok a `mplus` Ok b = Ok a
- instance (MonadError String) Excep where
- throwError = Err
- Err l `catchError` h = h l
- Ok r `catchError` _ = Ok r
- (?/) :: (MonadError String m) => Double -> Double -> m Double
- x ?/ 0 = throwError "Division by 0."
- x ?/ y = return $ x / y
- example :: Double -> Double -> Excep String
- example x y = action `catchError` return where
- action = do
- q <- x ?/ y
- guard (q >=0)
- if q > 100 then do
- {-100 <- return q-}
- throwError "Monad.fail error."
- else
- return $ show q
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement