Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I underscore (ignore) type variables when creating a type class instance?

Here's a simple example:

data T a b = T a b deriving (Show)

instance Functor (T a) where
    fmap f (T x y) = T x (f y)

Why can't I omit the a in the instance declaration, and write something like:

instance Functor (T _) where

?

The type of a is obviously irrelevant for that instance! (And it would be really more readable in my opinion).

It's obvious we can ignore values of function parameters. Why not allow ignoring values of type variables?

like image 419
Bartek Banachewicz Avatar asked Jan 14 '15 14:01

Bartek Banachewicz


1 Answers

In short, type class instance parameters don't abide the rules of pattern matching, for which _ is designed to work as I'd like it to.

Haskell explicitely forbids creating instances where type variables repeat:

An instance declaration introduces an instance of a class. Let class cx => C u where { cbody } be a class declaration. The general form of the corresponding instance declaration is: instance cx′ => C (T u1 … uk) where { d } where k ≥ 0. The type (T u1 … uk) must take the form of a type constructor T applied to simple type variables u1, … uk; furthermore, T must not be a type synonym, and the ui must all be distinct.

This prohibits instance declarations such as:

 instance C (a,a) where ...  
 instance C (Int,a) where ...  
 instance C [[a]] where ...

The possibility to "type-pattern-match" in instance declarations is most probably way more complicated and might have different implications, so I can see why _ wasn't introduced;.

like image 112
Bartek Banachewicz Avatar answered Jan 31 '23 07:01

Bartek Banachewicz