[Haskell-beginners] Type Class question

Brent Yorgey byorgey at seas.upenn.edu
Tue Jun 2 16:47:25 EDT 2009


On Tue, Jun 02, 2009 at 03:44:48PM -0400, Malik H wrote:
> I am reading article "Fun with type functions" and I have a few
> questions regarding examples presented in it. Here is the code
> 
> class Add a b where
>     type SumTy a b
>     add :: a -> b -> SumTy a b
> 
> instance (Add Integer a) => Add Integer [a] where
>     type SumTy Integer [a] = [SumTy Integer a]
>     add x y = map (add x) y
> 
> Here are my questions:
> 1. Is type "SumTy Integer [a]" visible outside 'Add' instance?

Yes.

> 2. If yes, how would you create and instance of that type without
> using 'add' function?

Notice that the 'type' declaration just sets up an equality between
types.  So 'SumTy Integer [a]' is *the same as* [SumTy Integer a].
Now, what is 'SumTy Integer a'?  Well, it depends on what a is.  In
the paper they give an example when a = Double, then SumTy Integer
Double = Double.  So we see that

  SumTy Integer [Double] = [SumTy Integer Double] = [Double].

So, since 'SumTy Integer [Double]' is really just a fancy way of
saying [Double], you can create a value of that type in any way you
would normally create a value of type [Double].  For example,

  [3.0, 2.9, 6.6] :: SumTy Integer [Double]

> 3. Will function 'add x y' create the following structure [SumTy x y1,
> SumTy x y2, etc...]? If not, what is 'add x y' creates?

No, SumTy is a function on *types*, and x and y are *values*.  So
saying 'SumTy x y1' does not make sense.  Suppose

  x = 3 :: Integer
  y = [3.1, 2.9] :: [Double]

then

  add x y = [6.1, 5.9] :: SumTy Integer [Double]

> 4. How to print the result of 'add x y'?

It depends on the type of x and y; but from above I hope you can see
that there is nothing special about the values you get out of 'add';
the result of 'add' will just be a normal value whose type is
determined by the 'SumTy' type function.

> 
> Also, I understand the following
> "instance (Ord a) => Monad a where ...."
> 
> as type of the 'a' must be an extension of type Ord.
> How shall I understand code below?
>   "instance (Add Integer a) => Add Integer [a]"

This means that we can add an Integer to a list of a's, as long as we
know how to add an Integer to something of type a.


-Brent


More information about the Beginners mailing list