// this works
instance BEncodable a => BEncodable [a] where
encode = encodeList;
;
// this doesn't
instance Num a => BEncodable a where
encode = encodeNum;
;
Why can't I say that all types which are Nums are also BEncodable?
Instance declarations take the basic form (ignoring syntactic sugar):
instance constraints => class_name (type_constructor type_variable*)
where ...
In particular, there must be a specific type constructor at the root
of the instance type, such as List, in your example:
instance BEncodable a => BEncodable [a] where ...
The reason for this, is that without this restriction, if one declared
an instance such as:
//not legal CAL
instance Num a => BEncodable a where
then any other instance declaration would overlap with this instance
declaration, and so would result in an overlapping instance
compilation error i.e. this would be the only legal instance
declaration for BEncodable. If that is indeed the intent, then in fact
all types which are BEncodable are also Nums, so that one could just
make the type class declaration reflect this i.e.
public class Num a => BEncodable a where ...
Cheers,
Bo
Thanks for the very clear explanation.
So CAL matches the constructor without looking at the constraint.
Is what I'm trying to do equivalent to GHCs 'overlapping instances'
extension?
Thanks,
Tom
Bo