对泛型的类型添加约束,从而使泛型类型的变量具有某种通用操作。
再使用这些操作,参与到其它操作中。
In , a type class is a construct that supports . This is achieved by adding constraints to type variables in types. Such a constraint typically involves a type class T
and a a
, and means that a
can only be instantiated to a type whose members support the overloaded operations associated with T
.
The programmer defines a type class by specifying a set of function or constant names, together with their respective types, that must exist for every type that belongs to the class. In Haskell, types can be parameterized; a type class Eq
intended to contain types that admit equality would be declared in the following way:
-
class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool