> import Prelude hiding (div) > import qualified Prelude ------------------------------------------------------------ Language E + div exception + abstracted exception threading ------------------------------------------------------------ > add :: Either Int String -> Either Int String -> Either Int String > add = exceptionHandle (\x y -> Left (x + y)) > sub :: Either Int String -> Either Int String -> Either Int String > sub = exceptionHandle (\x y -> Left (x - y)) > div :: Either Int String -> Either Int String -> Either Int String > div = exceptionHandle (\x y -> if y==0 then Right "Exception: Divide by zero" > else Left (x `Prelude.div` y)) > mul :: Either Int String -> Either Int String -> Either Int String > mul = exceptionHandle (\x y -> Left (x * y)) > exceptionHandle :: (a -> a -> Either a String) > -> Either a String > -> Either a String > -> Either a String > exceptionHandle f x y = case x of > Right e -> Right e > Left x' -> case y of > Right e' -> Right e' > Left y' -> f x' y' ------------------------------------------------------------ Examples ------------------------------------------------------------ x = Left 3 > x = add (Left 1) (Left 2) y = Left 17 > y = add (mul (Left 3) (Left 4)) (Left 5) z = Right "Exception: Divide by zero" > z = div (Left 1) (Left 0) w = Right "Exception: Divide by zero" > w = add (Left 1) (div (Left 1) (Left 0))