haskpy.typeclasses¶
Typeclasses define properties that types may have.
Typeclass is a term used in Haskell. The term “typeclass” could roughly be
translated as “interface” in object-oriented programming languages. Each
typeclass defines some properties that a type can have, for instance, that
values of a type can be compared for equality (i.e, Eq
typeclass).
Types can be instances of multiple typeclasses.
When a type implements an interface defined by a typeclass, the type is said to be an instance of the typeclass in Haskell terminology. In HaskPy, the typeclasses are implemented as base classes and the types inherit the typeclasses. So, types are also classes and they aren’t “instances” of typeclasses but subclasses in Python terminology. However, we will use the Haskellish terminology and say that types are instances of typeclasses although they are implemented as subclasses.
Each typeclass can define methods or attributes that an instance must
implement. For instance, Eq
instances must implement either
Eq.__eq__()
or Eq.__ne__()
method to tell how two values of
that type are compared for (in)equality. The typeclass can also define default
implementations for some of the methods. Each typeclass will tell what is the
minimum complete definition.
Parametric polymorphism means that a value can be of any type that is an
instance of some typeclass. For instance, function eq()
takes two
arguments that can be of any type that is an instance of Eq
. But
because how the values should be compared, depends on the type the
implementation of eq()
depends on the type. This is achieved in a
pythonic way so that eq()
calls Eq.__eq__()
method of the
first argument.
That is how parametric polymorphism in general is implemented in HaskPy. The
implementations are provided by methods/attributes of the type so Python can
find the correct implementation easily. Then, top-level functions act as thin
wrappers over these methods. For instance, map()
calls
Functor.map()
method of the second argument and bind()
calls Monad.bind()
method of the first argument.
Todo
Laws!
Todo
Syntax! Eq a => a -> a -> Bool
Typeclasses for basic properties:
Equality and inequality for types |
|
TODO |
|
Hashability for types |
|
TODO |
|
TODO |
Container-like typeclasses:
Functors represent types that can be mapped over |
|
Apply typeclass |
|
Bind typeclass |
|
Applicatives |
|
Monads are lovely |
|
Contravariant functors |
|
Profunctors |
|
Cartesian functors |
|
Cocartesian functors |
|
TODO |
Typeclasses for types that can be merged:
Semigroups |
|
Monoids |
Struture that can be manipulated or traversed:
Struture that can be squashed |
|
Traversable structure can be traversed, acccumulating results and effects |
Abstract base class of the typeclasses:
Basis for typeclasses |
Read more at Typeclassopedia.