If you look at the example for catches:
f = expr `catches` [Handler (\ (ex :: ArithException) -> handleArith ex),
Handler (\ (ex :: IOException) -> handleIO ex)]
It looks like catches has defined a custom mechanism to match on patterns (the two exception types). Am I mistaken, or can this be generalized to allow one to define a function that can take lambda functions that match on a certain pattern?
Edit: FYI below is the GHC source for catches. If someone can shed some light on how this works it would be great.
catches :: IO a -> [Handler a] -> IO a
catches io handlers = io `catch` catchesHandler handlers
catchesHandler :: [Handler a] -> SomeException -> IO a
catchesHandler handlers e = foldr tryHandler (throw e) handlers
where tryHandler (Handler handler) res
= case fromException e of
Just e' -> handler e'
Nothing -> res
This is the Scoped Type Variables GHC extension at work. Follow the link to learn more.
Basically, you define an assertion about type that have to be met by the patter before it can match. So, yeah, it is akin to guards, but not completely so.
How this particular example works? Dive into sources of “base” library to find out that:
We see that
IOExceptionandArithExceptionare different types implementing the typeclassException. We also see thattoException/fromExceptionis a wrapping/unwrapping mechanism that allows one to convert values of typeExceptionto/from values of typesIOException,ArithException, etc.So, we could’ve written:
Suppose that
IOExceptionhappens. WhencatchesHandlerprocesses first element of the handlers list, it callstryHandler, which callsfromException. From the definition oftryHandlerit follows that return type of thefromExceptionshould be the same as argument ofhandleArith. On the other hand,eis of type Exception, namely – (IOException …). So, the types play out this way (this is not a valid haskell, but I hope that you get my point):From the
instance Exception IOException ...it follows immediately that the result isNothing, so this handler is skipped. By the same reasoning the following handler would be called, becausefromExceptionwould return(Just (IOException ...)).So, you’ve used type signatures of
handleArithandhandleIOto specify when each of them would be called, andfromException/toExceptionmade sure that it happened this way.If you want to, you could also constraint types of
handleIOandhandleArithinside the definition off, using scoped type variables. Arguably, this could give you better readability.Finalizing, Scoped Type Variables are not a primary players here. They are just used for convenience. Main machinery for playing this kind of tricks is
fromException/toExceptionand friends. Scoped Type Variables just allow you to have syntax which more closely resemble guard patterns.