-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path30.02-why-some-exception.hs
37 lines (27 loc) · 1020 Bytes
/
30.02-why-some-exception.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GADTs #-}
module WhySomeException where
import Control.Exception (ArithException (..), AsyncException (..))
import Data.Typeable
data MyException = forall e . (Show e, Typeable e) => MyException e
instance Show MyException where
showsPrec p (MyException e) = showsPrec p e
multiError :: Int -> Either MyException Int
multiError n = case n of
0 -> Left (MyException DivideByZero)
1 -> Left (MyException StackOverflow)
_ -> Right n
data SomeError = Arith ArithException
| Async AsyncException
| SomethingElse
deriving Show
discriminateError :: MyException -> SomeError
discriminateError (MyException e) =
case cast e of
Just arith -> Arith arith
Nothing ->
case cast e of
Just async -> Async async
Nothing -> SomethingElse
runDisc :: Int -> SomeError
runDisc n = either discriminateError (const SomethingElse) (multiError n)