Skip to content

Typeclass Theories

Each TypeclassTheory declares the sorts, operations, and laws one type class introduces (type class hierarchy), and the classes it extends (Moggi, 1991; Wadler, 1992). The class's panproto theory is the colimit, computed by the theory engine, of a diagram with one node per class of its extension closure and one theory inclusion per extension edge, so a shared ancestor is shared because the inclusions relate it, and the composition's provenance names the class that declared each law. The laws are stated first-order over a universe of combinators. The theories are ThCombinators, ThFunctor, ThApplicative, ThMonad, ThAlternative, ThMonadPlus, ThMonadTrans, ThFoldable, and ThTraversable, and their denotations are given in the semantics.

theories

Theories of the typeclass hierarchy, composed by colimit.

Each typeclass of quivers.monadic.typeclasses has a TypeclassTheory here: the sorts, operations, and laws the class introduces, and the classes it extends. TypeclassTheory.composition builds the class's panproto theory as the colimit of a diagram with one node per class in its extension closure, holding that class's own laws over its closure's signature, and one node per extended class, holding that class's signature without laws. Each extension is the span of theory inclusions from the parent's signature into the parent and into the child, so the two are glued along exactly what the parent's closure declares. The colimit is computed by panproto's engine through quivers.gat in explicit-identity mode, so two classes share a symbol only when the extension edges relate it, and the composition's provenance records which class declared each law. ThMonadPlus, for instance, is the colimit of ThMonad and ThAlternative glued along ThApplicative, and its provenance sends each applicative law to the node ThApplicative.

The laws are stated first-order in one universe sort U, in the combinatory style: functions are elements of U, app(f, x) applies one, and id(), dot() (curried composition) and applyto(y) (the section λf. f y) are combinators with their defining equations in ThCombinators. A law that binds a variable under a lambda is stated with a combinator that names the lambda, given by its own defining equation: kleisli(k, h) for λx. bind(k x, h), unit() for pure as a function, liftfn() for lift as a function.

What the encoding states:

  • ThFunctor: fmap with the identity and composition laws.
  • ThApplicative: pure and apply with the identity, homomorphism, interchange, and composition laws, and the coherence fmap(f, v) = apply(pure(f), v).
  • ThMonad: bind with the left unit, right unit, and associativity laws, and join defined as bind(mm, id()).
  • ThAlternative: empty and alt with the monoid laws.
  • ThMonadPlus: the left zero law bind(empty(), k) = empty().
  • ThMonadTrans: lift with its two laws, between an inner monad (pure_inner, bind_inner) and the transformed one (pure_outer, bind_outer); the monad laws of each are those of ThMonad along a view, and are not restated.
  • ThFoldable: foldr, which has no laws of its own.
  • ThTraversable: traverse at the identity applicative, with the identity law and the coherence of traverse with fmap. The naturality and composition laws quantify over applicative transformations and composite applicatives, which a signature with one universe sort cannot range over; they are not encoded.

The encoding is untyped: one sort holds plain values, functions, and values in context alike, so a model may interpret terms the typed reading would reject. The laws are equations every lawful instance satisfies under the evident interpretation; registering an instance does not check them.

The arrow tower in quivers.arrows.theories is built the same way.

ThCombinators module-attribute

ThCombinators = TypeclassTheory(name='ThCombinators', sorts=(UNIVERSE,), operations=(operation('app', 'f', 'x'), operation('id'), operation('dot'), operation('applyto', 'y')), equations=(law('combinator_id', 'app(id(), x)', 'x'), law('combinator_dot', 'app(app(app(dot(), g), f), x)', 'app(g, app(f, x))'), law('combinator_applyto', 'app(applyto(y), f)', 'app(f, y)')))

The combinators every typeclass theory states its laws with.

ThFunctor module-attribute

ThFunctor = TypeclassTheory(name='ThFunctor', operations=(operation('fmap', 'f', 'xs'),), equations=(law('functor_identity', 'fmap(id(), xs)', 'xs'), law('functor_composition', 'fmap(app(app(dot(), g), f), xs)', 'fmap(g, fmap(f, xs))')), extends=(ThCombinators,))

The theory of Functor.

ThApplicative module-attribute

ThApplicative = TypeclassTheory(name='ThApplicative', operations=(operation('pure', 'x'), operation('apply', 'u', 'v')), equations=(law('applicative_identity', 'apply(pure(id()), v)', 'v'), law('applicative_homomorphism', 'apply(pure(f), pure(x))', 'pure(app(f, x))'), law('applicative_interchange', 'apply(u, pure(y))', 'apply(pure(applyto(y)), u)'), law('applicative_composition', 'apply(apply(apply(pure(dot()), u), v), w)', 'apply(u, apply(v, w))'), law('applicative_fmap', 'fmap(f, v)', 'apply(pure(f), v)')), extends=(ThFunctor,))

The theory of Applicative.

ThMonad module-attribute

ThMonad = TypeclassTheory(name='ThMonad', operations=(operation('bind', 'm', 'k'), operation('unit'), operation('kleisli', 'k', 'h'), operation('join', 'mm')), equations=(law('monad_left_unit', 'bind(pure(x), k)', 'app(k, x)'), law('monad_right_unit', 'bind(m, unit())', 'm'), law('monad_associativity', 'bind(bind(m, k), h)', 'bind(m, kleisli(k, h))'), law('monad_unit', 'app(unit(), x)', 'pure(x)'), law('monad_kleisli', 'app(kleisli(k, h), x)', 'bind(app(k, x), h)'), law('monad_join', 'join(mm)', 'bind(mm, id())')), extends=(ThApplicative,))

The theory of Monad.

ThAlternative module-attribute

ThAlternative = TypeclassTheory(name='ThAlternative', operations=(operation('empty'), operation('alt', 'x', 'y')), equations=(law('alternative_left_identity', 'alt(empty(), x)', 'x'), law('alternative_right_identity', 'alt(x, empty())', 'x'), law('alternative_associativity', 'alt(alt(x, y), z)', 'alt(x, alt(y, z))')), extends=(ThApplicative,))

The theory of Alternative.

ThMonadPlus module-attribute

ThMonadPlus = TypeclassTheory(name='ThMonadPlus', equations=(law('monadplus_left_zero', 'bind(empty(), k)', 'empty()'),), extends=(ThMonad, ThAlternative))

The theory of MonadPlus: ThMonad and ThAlternative glued along ThApplicative.

ThMonadTrans module-attribute

ThMonadTrans = TypeclassTheory(name='ThMonadTrans', operations=(operation('pure_inner', 'x'), operation('bind_inner', 'm', 'k'), operation('pure_outer', 'x'), operation('bind_outer', 'm', 'k'), operation('lift', 'm'), operation('liftfn')), equations=(law('trans_liftfn', 'app(liftfn(), m)', 'lift(m)'), law('trans_lift_pure', 'lift(pure_inner(x))', 'pure_outer(x)'), law('trans_lift_bind', 'lift(bind_inner(m, k))', 'bind_outer(lift(m), app(app(dot(), liftfn()), k))')), extends=(ThCombinators,))

The theory of MonadTrans.

ThFoldable module-attribute

ThFoldable = TypeclassTheory(name='ThFoldable', operations=(operation('foldr', 'f', 'z', 't'),), extends=(ThCombinators,))

The theory of Foldable.

ThTraversable module-attribute

ThTraversable = TypeclassTheory(name='ThTraversable', operations=(operation('traverse', 'f', 't'), operation('ident', 'x'), operation('identfn'), operation('runident', 'i')), equations=(law('identity_constructor', 'app(identfn(), x)', 'ident(x)'), law('identity_run', 'runident(ident(x))', 'x'), law('traversable_identity', 'traverse(identfn(), t)', 'ident(t)'), law('traversable_fmap', 'fmap(f, t)', 'runident(traverse(app(app(dot(), identfn()), f), t))')), extends=(ThFunctor, ThFoldable))

The theory of Traversable: ThFunctor and ThFoldable glued along ThCombinators.

Parameter didactic-model

Parameter(*, name: str, sort: str = UNIVERSE)

Bases: Model

One input of an operation.

PARAMETER DESCRIPTION
name

The parameter's name, which equations may use as a variable.

TYPE: str

sort

Its sort.

TYPE: str DEFAULT: UNIVERSE

OperationDecl didactic-model

OperationDecl(*, name: str, inputs: tuple[Parameter, ...] = (), output: str = UNIVERSE)

Bases: Model

An operation a typeclass theory declares.

PARAMETER DESCRIPTION
name

The operation's name.

TYPE: str

inputs

Its inputs.

TYPE: tuple of Parameter DEFAULT: ()

output

Its output sort.

TYPE: str DEFAULT: UNIVERSE

signature

signature() -> str

Render as name : (p : S, ...) -> T.

RETURNS DESCRIPTION
str

The signature.

Source code in src/quivers/monadic/theories.py
def signature(self) -> str:
    """Render as ``name : (p : S, ...) -> T``.

    Returns
    -------
    str
        The signature.
    """
    inputs = ", ".join(f"{p.name} : {p.sort}" for p in self.inputs)
    return f"{self.name} : ({inputs}) -> {self.output}"

LawDecl didactic-model

LawDecl(*, name: str, lhs: str, rhs: str)

Bases: Model

A law a typeclass theory declares, as an equation between terms.

PARAMETER DESCRIPTION
name

The law's name.

TYPE: str

lhs

The left-hand side, in the theory-DSL term syntax.

TYPE: str

rhs

The right-hand side.

TYPE: str

statement

statement() -> str

Render as lhs = rhs.

RETURNS DESCRIPTION
str

The equation.

Source code in src/quivers/monadic/theories.py
def statement(self) -> str:
    """Render as ``lhs = rhs``.

    Returns
    -------
    str
        The equation.
    """
    return f"{self.lhs} = {self.rhs}"

TypeclassTheory didactic-model

TypeclassTheory(*, name: str, sorts: tuple[str, ...] = (), operations: tuple[OperationDecl, ...] = (), equations: tuple[LawDecl, ...] = (), extends: tuple[TypeclassTheory, ...] = ())

Bases: Model

The sorts, operations, and laws one typeclass introduces, and what it extends.

PARAMETER DESCRIPTION
name

The theory's name (e.g. "ThFunctor"), also its node label in compositions; it contains neither . nor #.

TYPE: str

sorts

The sorts the class introduces.

TYPE: tuple of str DEFAULT: ()

operations

The operations the class introduces.

TYPE: tuple of OperationDecl DEFAULT: ()

equations

The laws the class introduces.

TYPE: tuple of LawDecl DEFAULT: ()

extends

The classes it extends.

TYPE: tuple of TypeclassTheory DEFAULT: ()

closure

closure() -> tuple[TypeclassTheory, ...]

This class and every class it extends, transitively.

RETURNS DESCRIPTION
tuple of TypeclassTheory

Each class once, ancestors before descendants, in the order of a depth-first walk of extends.

RAISES DESCRIPTION
ValueError

If two different classes of the closure share a name.

Source code in src/quivers/monadic/theories.py
def closure(self) -> tuple[TypeclassTheory, ...]:
    """This class and every class it extends, transitively.

    Returns
    -------
    tuple of TypeclassTheory
        Each class once, ancestors before descendants, in the order
        of a depth-first walk of ``extends``.

    Raises
    ------
    ValueError
        If two different classes of the closure share a name.
    """
    return _closure(self)

local_theory

local_theory() -> Theory

This class's own laws over its closure's signature.

RETURNS DESCRIPTION
Theory

A theory named after the class whose sorts and operations are those every class of its closure declares, and whose equations are this class's laws alone.

RAISES DESCRIPTION
CompositionRefused

If two classes of the closure declare the same name, which would identify symbols no extension relates.

Source code in src/quivers/monadic/theories.py
def local_theory(self) -> panproto.Theory:
    """This class's own laws over its closure's signature.

    Returns
    -------
    panproto.Theory
        A theory named after the class whose sorts and operations
        are those every class of its closure declares, and whose
        equations are this class's laws alone.

    Raises
    ------
    CompositionRefused
        If two classes of the closure declare the same name, which
        would identify symbols no extension relates.
    """
    return _local_theory(self)

composition

composition() -> ComposedTheory

The class's theory as the colimit of its extension diagram.

RETURNS DESCRIPTION
ComposedTheory

The colimit, with one inclusion per class of the closure and provenance naming the class that declared each law.

RAISES DESCRIPTION
CompositionRefused

If panproto refuses the diagram.

Source code in src/quivers/monadic/theories.py
def composition(self) -> ComposedTheory:
    """The class's theory as the colimit of its extension diagram.

    Returns
    -------
    ComposedTheory
        The colimit, with one inclusion per class of the closure and
        provenance naming the class that declared each law.

    Raises
    ------
    CompositionRefused
        If panproto refuses the diagram.
    """
    return _composition(self)

theory

theory() -> Theory

The class's composed theory.

RETURNS DESCRIPTION
Theory

The colimit's theory.

Source code in src/quivers/monadic/theories.py
def theory(self) -> panproto.Theory:
    """The class's composed theory.

    Returns
    -------
    panproto.Theory
        The colimit's theory.
    """
    return composed_theory(self.composition())

operation

operation(name: str, *inputs: str) -> OperationDecl

An operation over the universe sort.

PARAMETER DESCRIPTION
name

The operation.

TYPE: str

*inputs

Its parameter names, each of the universe sort.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION
OperationDecl

The declaration.

Source code in src/quivers/monadic/theories.py
def operation(name: str, *inputs: str) -> OperationDecl:
    """An operation over the universe sort.

    Parameters
    ----------
    name : str
        The operation.
    *inputs : str
        Its parameter names, each of the universe sort.

    Returns
    -------
    OperationDecl
        The declaration.
    """
    return OperationDecl(name=name, inputs=tuple(Parameter(name=p) for p in inputs))

law

law(name: str, lhs: str, rhs: str) -> LawDecl

A law.

PARAMETER DESCRIPTION
name

The law.

TYPE: str

lhs

Its left-hand side.

TYPE: str

rhs

Its right-hand side.

TYPE: str

RETURNS DESCRIPTION
LawDecl

The declaration.

Source code in src/quivers/monadic/theories.py
def law(name: str, lhs: str, rhs: str) -> LawDecl:
    """A law.

    Parameters
    ----------
    name : str
        The law.
    lhs : str
        Its left-hand side.
    rhs : str
        Its right-hand side.

    Returns
    -------
    LawDecl
        The declaration.
    """
    return LawDecl(name=name, lhs=lhs, rhs=rhs)

The theory constants are documented on the monadic overview.

Cited sources

Eugenio Moggi. Notions of Computation and Monads. Information and Computation, 93(1):55–92, 1991. URL: https://www.sciencedirect.com/science/article/pii/0890540191900524, doi:10.1016/0890-5401(91)90052-4.

Philip Wadler. The Essence of Functional Programming. In Proceedings of the 19th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, 1–14. ACM, 1992. URL: https://doi.org/10.1145/143165.143169, doi:10.1145/143165.143169.