Haskell's type-defaulting rules defaults a type variable a with constraints (C1 a,...,Cn a) if:
- The type variable a appears in no other constraints
- All the classes Ci are standard.
- At least one of the classes Ci is numeric
This makes sense to me but it's also very limited: in practice it means that you always have to specify the type when it is ambiguous when you work with custom classes. For example, this doesn't compile:
class (Show a) => MyShow a where
myShow :: a -> String
myShow = show
instance (MyShow a) => MyShow (Maybe a) where
myShow Nothing = "Nothing"
myShow (Just x) = "Just " ++ (myShow x)
main = print $ myShow Nothing -- ambiguous
GHCi extends this set of rules in this way:
- All of the classes Ci are single-parameter type classes.
- At least one of the classes Ci is numeric, or is Show, Eq, or Ord.
and GHC has an extension called ExtendedDefaultRules that enable these rules. However this extension is very specific: it works only on GHC and with standard classes. For instance, one can think about libraries that don't use the standard library. In that case, the GHCi extension won't work.
My question is: the only way to extend the Haskell's type-defaulting rules like GHCi does is with compiler extensions? And more generic: is there a way to define type-defaulting based on some rules on the constraints in Haskell 98?
instance (MyShow a) => MyShow (Maybe a) where .... defaulting (Int). The compiler can check if the type is ambiguous and in that case default. In the case above Nothing would have type Maybe Int. Of course you can default only on types that satisfy the constraints. - mariop