Reputation: 35
What is the difference between ?
data SomeException = forall e . Exception e => SomeException e
data SomeException = Exception e => SomeException e
Why do we need forall ? link to source
Upvotes: 2
Views: 113
Reputation: 3805
The second variant doesn't even compile. You get:
error: Not in scope: type variable e
The reason is that it isn't clear which e
you are referring to. You can add e
as a type parameter on the left hand side:
data SomeException e = Exception e => SomeException e
However, this loses the point of having a SomeException
in the first place, which is to hide the details about which concrete exception is involved. Now any function taking SomeException e
as input would have to know about the type of e
, again.
forall e.
allows us to specify that we really don't care what data object is inside SomeException
as long as it is an instance of Exception
. That also means that we can't do anything with any SomeException
item except for what's contained in the type class Exception
.
You can read more about it in the Wikibook.
Upvotes: 3
Reputation: 2955
The first is called Existential type. The second one won't even compile.
Basically, you have to add forall
it if you want some variable to only appear in the right-hand side (the right side of =)
It allows you e.g. to create heterogeneous list, e.g. [SomeException]
could contain list of SomeException e
where e
is different for each element.
Upvotes: 3