IvoryScript further reading

Standard ad-hoc polymorphic type classes

IvoryScript supports type classes for ad-hoc polymorphism. This is one area where its type system is relatively conventional.

A type class describes a method, or group of methods, which may be provided for different types. For example:

         class Eq a where {
            (=) :: a -> a -> Bool
         }
      

states that values of a type a may support equality. An instance supplies the corresponding method for a particular type:

         instance Eq Int where {
         inline (=) = eqInt;
         }
         ...
         instance Eq Char where {
            inline (=) = eqChar;
         }
      

Allowing (=) to be used in different contexts, e.g.

         2 = 2;
         'a' = 'Z'
      

The type variable a remains polymorphic, while a class method declaration requires equality (in this case) to be available for its type instances .

Classes with more than one parameter

Type classes are not restricted to a single type parameter. A class may describe an operation involving two or more types.

The Cast class, which will be important in the next section, relates a source type to a destination type:

            class Cast a, b where {
               cast :: a -> b
            }
         

An instance can therefore provide conversion between particular types:

            instance Cast Int, Double where {
               ...
            }
         

Here class membership concerns the pair of types rather than either type in isolation.

Class methods as operators

Class methods need not have conventional function names. Operators may also be class methods, as with (=) above.

Another example is (.), a class method of Select. Different types can therefore provide their own behaviour for selection by name.

Type classes allow operations to be expressed in terms of the types which support them, while type variables allow those operations to remain polymorphic.

The next section uses this otherwise conventional mechanism for a particular purpose: reduction itself can be expressed as a type conversion.