Constrained instances

0 views
Skip to first unread message

Tom Davies

unread,
Jul 17, 2007, 2:49:03 AM7/17/07
to CAL Language Discussion
public class BEncodable a where
public encode :: a -> [Byte];
;

// 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?

bilic

unread,
Jul 17, 2007, 7:02:35 PM7/17/07
to CAL Language Discussion
Hi Tom,

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

Tom Davies

unread,
Jul 17, 2007, 7:31:54 PM7/17/07
to CAL Language Discussion
Hi 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

bilic

unread,
Jul 17, 2007, 9:44:03 PM7/17/07
to CAL Language Discussion
If you enable the overlapping instances extension in GHC, it would let
you declare e.g. "instance BEncodable [Int]", as well as "instance
BEncodable a => BEncodable [a]", but the declaration for "instance Num
a => BEncodable a" is not allowed. If you turn on their "undecidable
instances" flag though, the corresponding code compiles (but it might
not do what you want).

Bo

Reply all
Reply to author
Forward
0 new messages