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:
class (Show e) => Exception e where
toException :: e -> SomeException
fromException :: SomeException -> Maybe e
data SomeException = forall e . Exception e => SomeException e
instance Exception IOException where
toException = IOException
fromException (IOException e) = Just e
fromException _ = Nothing
instance Exception ArithException where
toException = ArithException
fromException (ArithException e) = Just e
fromException _ = Nothing
We see that IOException
and ArithException
are different types implementing the typeclass Exception
. We also see that toException/fromException
is a wrapping/unwrapping mechanism that allows one to convert values of type Exception
to/from values of types IOException
, ArithException
, etc.
So, we could've written:
f = expr `catches` [Handler handleArith,
Handler handleIO]
handleArith :: ArithException -> IO ()
handleArith ex = ....
handleIO :: IOException -> IO ()
handleIO ex = ....
Suppose that IOException
happens. When catchesHandler
processes first element of the handlers list, it calls tryHandler
, which calls fromException
. From the definition of tryHandler
it follows that return type of the fromException
should be the same as argument of handleArith
. On the other hand, e
is 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):
fromException :: (IOException ...) -> Maybe ArithException
From the instance Exception IOException ...
it follows immediately that the result is Nothing
, so this handler is skipped. By the same reasoning the following handler would be called, because fromException
would return (Just (IOException ...))
.
So, you've used type signatures of handleArith
and handleIO
to specify when each of them would be called, and fromException/toException
made sure that it happened this way.
If you want to, you could also constraint types of handleIO
and handleArith
inside the definition of f
, 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/toException
and friends. Scoped Type Variables just allow you to have syntax which more closely resemble guard patterns.