Type Classes and the StdEnv

Arjan van IJzendoorn arjanij@cs.kun.nl
Wed, 26 Nov 1997 10:03:04 +0100


Hi Nick,

>Why isn't there is a map class?

This is because there were no type constructor classes at the time
the StdEnv was written. To retain backward compatibility the function
has not been changed since. Subtle typing problems can occur if you
simply overload map. The following program demonstrates such a
problem. Changing "map" into the overloaded "map`" in "incAll" will
result in a compile-time error:

/*******************/

module a

import StdInt, StdList

incAll xs = map inc xs

Start = incAll nil

class Map f where
  map` :: (a -> b) (f a) -> f b

instance Map [] where
  map` f xs = map f xs

class Nil x where
  nil :: x Int

instance Nil [] where
  nil = []

/*******************/

As can be seen from the example, you can of course define your
own overloaded map. Because the name "map`" is not very
nice you may want consider defining an overloaded function "forAll":

class ForAll f where
  (forAll) infix 0 :: (a -> b) (f a) -> f b

instance ForAll [] where
  (forAll) f xs = map f xs

Now you can use it in the following way:

  doSomething forAll [1, 2, 3]
    where
      doSomething = fac

Greetings,
  Arjan