Advertisement
Guest User

Untitled

a guest
May 5th, 2015
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE FlexibleInstances #-}
  2. {-# LANGUAGE MultiParamTypeClasses #-}
  3. {-# LANGUAGE FlexibleContexts #-}
  4.  
  5. import Control.Monad.Error
  6. import Control.Applicative
  7.  
  8. data Excep a =  Err String | Ok a
  9.     deriving (Eq, Show)
  10.  
  11. instance Monad Excep where
  12.     return = Ok
  13.     Ok a >>= f = f a
  14.     Err a >>= _ = Err a
  15.  
  16. instance Applicative Excep where
  17.     pure  = return
  18.     (<*>) = ap
  19.  
  20. instance Functor Excep where
  21.     fmap = liftM
  22.  
  23. instance Alternative Excep where
  24.     (<|>) = mplus
  25.     empty = mzero
  26.  
  27. instance MonadPlus Excep where
  28.     mzero = Err "MonadPlus.mzero error."
  29.     Err _ `mplus` _ = Err "MonadPlus.mzero error."
  30.     _ `mplus` Err _  = Err "MonadPlus.mzero error."
  31.     Ok a `mplus` Ok b = Ok a
  32.  
  33. instance (MonadError String) Excep where
  34.     throwError = Err
  35.     Err  l `catchError` h = h l
  36.     Ok r `catchError` _ = Ok r
  37.  
  38. (?/) :: (MonadError String m) => Double -> Double -> m Double
  39. x ?/ 0 = throwError "Division by 0."
  40. x ?/ y = return $ x / y
  41.  
  42. example :: Double -> Double -> Excep String
  43. example x y = action  `catchError` return where
  44.   action = do
  45.     q <- x ?/ y
  46.     guard (q >=0)
  47.     if q  > 100 then do
  48.       {-100 <- return q-}
  49.       throwError "Monad.fail error."
  50.     else
  51.       return $ show q
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement