To promote flexibility, Haskell has a hierarchy of type classes. A type class in Haskell is a set of types, unlike the concept of a class from object-oriented programming. Specifically, a type class in Haskell is a set of types, all of which define certain functions. The definition of a type class declares the names and types of the functions that all members of that class must define. Thus, a type class is like an interface from object-oriented programming, particularly an interface in Java. The concept of a class from object-oriented programming, which is the analog of a type (not a type class) in Haskell, can implement several interfaces, which means it must provide definitions for the functions specified (i.e., prototyped) in each interface. Haskell types are made instances of type classes in a similar way. When a Haskell type is declared to be an instance of a type class, that type promises to provide definitions of the functions in the definition of that class (i.e., signature). In summary, a class in object-oriented programming and a type in Haskell are analogs of each other; an interface in object-oriented programming and a type class in Haskell are analogs of each other as well (Table C.1).
Table C.1 Conceptual Equivalence in Type Mnemonics Between Java and Haskell
Java | interface | class |
Haskell | type class | type |
The types Int and Integer are members of the Integral class, which is asubclass ofthe Real class. The types Float and Double are members of the Floating class, which is a subclass of the Fractional class. Num is the base class to which all numeric types belong. Other predefined Haskell type classes include Eq, Show, and Ord. A portion of the type class inheritance hierarchy in Haskell is shown in Figure C.1. The classes Eq and Show appear at the root of the hierarchy. The hierarchy involves multiple inheritance, which is akin to the ability of a Java class to implement more than one interface.
Returning to lines 7–8 in the previous transcript, the response 3 :: Num a => a (line 8) indicates that if type a is in the class Num, then 3 has the type a. In other words, 3 is of some type in the Num class. Such a type is called a qualified type or constrained type (Table C.2). The left-hand side of the => symbol—which here is in the form C a—is called the class constraint or context, where C is a type class and a is a type variable:
Table C.2 The General Form of a Qualified Type or Constrained Type and an Example
We encounter qualified types again in our discussion of tuples and user-defined functions in Section C.8 and Section C.9, respectively.
18.217.164.143