Skip to content

Typeclass Hierarchy

The type classes Functor, Applicative, Monad, Alternative, MonadPlus, Foldable, Traversable, and MonadTrans group the operations for mapping, combining, and sequencing computations, each as an abstract base class with laws (Moggi, 1991; Wadler, 1992). A functor law, for instance, requires two successive maps to equal one map of the composite function. An applicative combines computations whose structure is fixed before their results are known (McBride and Paterson, 2008), while monadic bind can choose the next computation from an earlier result.

typeclasses

Haskell-style typeclass hierarchy for compositional effects.

This module defines the abstract interfaces that effect instances implement. Each typeclass declares a set of operations that an instance must provide; default derivations are supplied where Haskell admits them. The class-extension lattice is:

Functor
├── Applicative
│   ├── Monad
│   └── Alternative
│       └── MonadPlus  (also extends Monad)
└── Traversable      (also extends Foldable)

Foldable

MonadTrans   — orthogonal: lifts an inner monad through a stacked
               transformer; not a sub-class of any of the above.

The quivers.stochastic.effect_lifts.class_directed_lifts schema-lifting machinery dispatches on which classes an effect inhabits, never on the effect's identity, so user-defined effects extend the framework automatically.

Each typeclass also has a theory in quivers.monadic.theories, which states the equations an instance is expected to satisfy. Class extension is realized there as theory inclusion: a class's theory is the colimit, computed by panproto, of a diagram of its own laws and those of every class it extends, glued along the inclusions of their shared ancestors. Registering an instance does not prove that its operations satisfy those equations.

References

For applicative programming, see McBride and Paterson (2008); for arrows, see Hughes (2000). Algebraic effects and handlers are illustrated in Bauer and Pretnar (2015). Their use in natural-language composition is developed in the forthcoming book Bumford and Charlow (forthcoming).

Typeclass

Typeclass = type[Functor] | type[Foldable] | type[MonadTrans]

One of the classes of the hierarchy, or a user class extending one.

Carrier

Carrier = str

What an instance is an instance at: the name of the structure it acts on.

InstanceBuilder

InstanceBuilder = Callable[..., Functor | Foldable | MonadTrans]

Builds an instance from the instances its requirements resolved to.

Functor

Bases: ABC

Functor: an endofunctor on (V-enriched) finite sets.

A Functor instance carries:

  • fmap_obj — the type-level action F : SetObject → SetObject.
  • fmap — the morphism-level action sending f : A → B to F(f) : F(A) → F(B).

Functor laws:

  • identity: F(id_A) = id_{F(A)}
  • composition: F(g ∘ f) = F(g) ∘ F(f)

Both laws are documented and runtime-checkable in quivers.monadic.laws.

fmap_obj abstractmethod

fmap_obj(A: SetObject) -> SetObject

The type-level action F(A).

Source code in src/quivers/monadic/typeclasses.py
@abstractmethod
def fmap_obj(self, A: SetObject) -> SetObject:
    """The type-level action ``F(A)``."""

fmap abstractmethod

fmap(A: SetObject, B: SetObject, f: Morphism) -> Morphism

The morphism-level action F(f) : F(A) → F(B).

Source code in src/quivers/monadic/typeclasses.py
@abstractmethod
def fmap(self, A: SetObject, B: SetObject, f: Morphism) -> Morphism:
    """The morphism-level action ``F(f) : F(A) → F(B)``."""

Applicative

Bases: Functor, ABC

Applicative functor: pure + apply.

Adds:

  • pure — the unit η_A : A → F(A).
  • apply — the application combinator F(A → B) ⊗ F(A) → F(B).

Applicative laws McBride and Paterson (2008):

  • identity: apply(pure(id), v) = v
  • homomorphism: apply(pure(f), pure(x)) = pure(f x)
  • interchange: apply(u, pure(y)) = apply(pure(λf. f y), u)
  • composition: apply(apply(apply(pure(∘), u), v), w) = apply(u, apply(v, w))

The default fmap derivation fmap(f) = apply(pure(f), -) is provided.

pure abstractmethod

pure(A: SetObject) -> Morphism

η_A : A → F(A).

Source code in src/quivers/monadic/typeclasses.py
@abstractmethod
def pure(self, A: SetObject) -> Morphism:
    """``η_A : A → F(A)``."""

apply

apply(A: SetObject, B: SetObject) -> Morphism

F(A → B) ⊗ F(A) → F(B).

Realised in V-Rel as a parameterized binary operation; the concrete construction depends on the instance and on the internal-hom representation of the underlying enriched category. The default implementation raises NotImplementedError; concrete instances override.

Source code in src/quivers/monadic/typeclasses.py
def apply(self, A: SetObject, B: SetObject) -> Morphism:
    """``F(A → B) ⊗ F(A) → F(B)``.

    Realised in V-Rel as a parameterized binary operation; the
    concrete construction depends on the instance and on the
    internal-hom representation of the underlying enriched
    category. The default implementation raises
    `NotImplementedError`; concrete instances override.
    """
    raise NotImplementedError(
        f"{type(self).__name__}.apply requires an internal-hom "
        "construction; override on the concrete instance"
    )

lift_a2

lift_a2(A: SetObject, B: SetObject, C: SetObject, f: Morphism) -> Morphism

Apply a binary function under the Applicative.

Default derivation: liftA2 f x y = apply(fmap(curry f, x), y), where curry f : A → [B → C] reads f as a function into the finite function space. Concrete instances may override for efficiency.

PARAMETER DESCRIPTION
A

The factors and the codomain of f.

TYPE: SetObject

B

The factors and the codomain of f.

TYPE: SetObject

C

The factors and the codomain of f.

TYPE: SetObject

f

A function A × B → C.

TYPE: Morphism

RETURNS DESCRIPTION
Morphism

F(A) ⊗ F(B) → F(C).

RAISES DESCRIPTION
ValueError

If f is not a function, so it has no curried form.

Source code in src/quivers/monadic/typeclasses.py
def lift_a2(
    self, A: SetObject, B: SetObject, C: SetObject, f: Morphism
) -> Morphism:
    """Apply a binary function under the Applicative.

    Default derivation: ``liftA2 f x y = apply(fmap(curry f, x), y)``,
    where ``curry f : A → [B → C]`` reads ``f`` as a function into the
    finite function space. Concrete instances may override for
    efficiency.

    Parameters
    ----------
    A, B, C : SetObject
        The factors and the codomain of ``f``.
    f : Morphism
        A function ``A × B → C``.

    Returns
    -------
    Morphism
        ``F(A) ⊗ F(B) → F(C)``.

    Raises
    ------
    ValueError
        If ``f`` is not a function, so it has no curried form.
    """
    curried = _curry(f, A, B, C)
    lifted = self.fmap(A, _function_space(B, C), curried)
    return (lifted @ id_morph(self.fmap_obj(B))) >> self.apply(B, C)

Monad

Bases: Applicative, ABC

Monad: pure + join (or bind).

Adds:

  • join — the multiplication μ_A : F(F(A)) → F(A).

The bind operation is derived via bind(m, k) = join(fmap(k)(m)).

Monad laws:

  • left unit: bind(pure(a), k) = k(a)
  • right unit: bind(m, pure) = m
  • associativity: bind(bind(m, k), h) = bind(m, λx. bind(k(x), h))

These are equivalent to:

  • join ∘ pure_F = id (left unit)
  • join ∘ F(pure) = id (right unit)
  • join ∘ F(join) = join ∘ join (associativity)

join abstractmethod

join(A: SetObject) -> Morphism

μ_A : F(F(A)) → F(A).

Source code in src/quivers/monadic/typeclasses.py
@abstractmethod
def join(self, A: SetObject) -> Morphism:
    """``μ_A : F(F(A)) → F(A)``."""

bind

bind(A: SetObject, B: SetObject, k: Morphism) -> Morphism

Monadic bind of a fixed continuation: F(A) → F(B).

Default derivation: bind(m, k) = join_B(fmap(k)(m)). Override on the concrete instance for a more direct realisation.

PARAMETER DESCRIPTION
A

The value types before and after the continuation.

TYPE: SetObject

B

The value types before and after the continuation.

TYPE: SetObject

k

The continuation A → F(B).

TYPE: Morphism

RETURNS DESCRIPTION
Morphism

fmap(k) >> join_B.

Source code in src/quivers/monadic/typeclasses.py
def bind(self, A: SetObject, B: SetObject, k: Morphism) -> Morphism:
    """Monadic bind of a fixed continuation: ``F(A) → F(B)``.

    Default derivation: ``bind(m, k) = join_B(fmap(k)(m))``. Override
    on the concrete instance for a more direct realisation.

    Parameters
    ----------
    A, B : SetObject
        The value types before and after the continuation.
    k : Morphism
        The continuation ``A → F(B)``.

    Returns
    -------
    Morphism
        ``fmap(k) >> join_B``.
    """
    return self.fmap(A, self.fmap_obj(B), k) >> self.join(B)

Alternative

Bases: Applicative, ABC

Alternative: an Applicative with empty + alt.

Adds:

  • empty — the bottom element ⊥_A : 1 → F(A).
  • alt — pointwise alternative F(A) ⊗ F(A) → F(A).

Alternative laws:

  • identity: alt(empty, x) = x = alt(x, empty)
  • associativity: alt(alt(x, y), z) = alt(x, alt(y, z))
  • left zero (when also a Monad): bind(empty, k) = empty

empty abstractmethod

empty(A: SetObject) -> Morphism

⊥_A : 1 → F(A).

Source code in src/quivers/monadic/typeclasses.py
@abstractmethod
def empty(self, A: SetObject) -> Morphism:
    """``⊥_A : 1 → F(A)``."""

alt abstractmethod

alt(A: SetObject) -> Morphism

F(A) ⊗ F(A) → F(A).

Source code in src/quivers/monadic/typeclasses.py
@abstractmethod
def alt(self, A: SetObject) -> Morphism:
    """``F(A) ⊗ F(A) → F(A)``."""

MonadPlus

Bases: Monad, Alternative, ABC

Monad + Alternative: a Monad whose F is also Alternative.

No new operations; the diamond inheritance picks up both join (from Monad) and empty / alt (from Alternative). Adds the left-zero law: bind(empty, k) = empty (already documented under Alternative).

Foldable

Bases: ABC

Foldable: support a catamorphism-like fold.

Used by Hamblin-style alternative semantics to collapse a structure of alternatives down to a single value. The minimal interface is foldr; richer combinators are derivable.

foldr abstractmethod

foldr(A: SetObject, B: SetObject) -> Morphism

(A ⊗ B → B) ⊗ B ⊗ F(A) → B.

Source code in src/quivers/monadic/typeclasses.py
@abstractmethod
def foldr(self, A: SetObject, B: SetObject) -> Morphism:
    """``(A ⊗ B → B) ⊗ B ⊗ F(A) → B``."""

Traversable

Bases: Functor, Foldable, ABC

Traversable: distribute an Applicative action through a structure.

Adds traverse: given an Applicative G and a morphism f : A → G(B), produces F(A) → G(F(B)). This supports distributing an effectful computation through a traversable structure, including applications to scope and alternatives Bumford and Charlow (forthcoming).

The traversal interface is required to satisfy the following laws:

  • naturality: t ∘ traverse(f) = traverse(t ∘ f) for any applicative natural transformation t.
  • identity: traverse(pure_Identity) = pure_Identity
  • composition: traverse(Compose ∘ f) = Compose ∘ fmap(traverse(g)) ∘ traverse(f)

traverse abstractmethod

traverse(A: SetObject, B: SetObject, applicative: Applicative, f: Morphism) -> Morphism

F(A) → G(F(B)) for an Applicative G and f : A → G(B).

Source code in src/quivers/monadic/typeclasses.py
@abstractmethod
def traverse(
    self, A: SetObject, B: SetObject, applicative: Applicative, f: Morphism
) -> Morphism:
    """``F(A) → G(F(B))`` for an Applicative ``G`` and ``f : A → G(B)``."""

MonadTrans

Bases: ABC

Monad transformer: lift an inner monad to a stacked monad.

A MonadTrans instance T provides lift, embedding an inner-monad Kleisli arrow into the transformer. The class is orthogonal to the Functor/Applicative/Monad tower: transformers are themselves monads (when applied to a base monad), but the transformer interface is the lift, not the bind.

Lift laws:

  • lift ∘ pure_m = pure_{T(m)}
  • lift(bind_m(x, k)) = bind_{T(m)}(lift(x), lift ∘ k)

lift abstractmethod

lift(m: Monad, A: SetObject) -> Morphism

m(A) → T(m)(A).

Source code in src/quivers/monadic/typeclasses.py
@abstractmethod
def lift(self, m: Monad, A: SetObject) -> Morphism:
    """``m(A) → T(m)(A)``."""

ClassSignature didactic-model

ClassSignature(*, name: str, operations: tuple[str, ...] = (), extends: tuple[str, ...] = (), laws: tuple[str, ...] = ())

Bases: Model

A typeclass read as a signature, as QVR reads signature S.

A class states operations and laws, as a QVR signature states computations and effect laws; an instance is an object that matches the signature, as a module is. QVR's implicit module parameters and the Python classes therefore share one notion of instance: a match, checked item by item, found by coherent tabled resolution.

ATTRIBUTE DESCRIPTION
name

The class's name.

TYPE: str

operations

Every operation an instance must implement: the class's own abstract operations and those of every class it extends, sorted.

TYPE: tuple[str, ...]

extends

The classes it extends directly.

TYPE: tuple[str, ...]

laws

The laws of its theory (quivers.monadic.theories), which an instance's operations are expected to satisfy; a match records them as obligations, assumed rather than checked.

TYPE: tuple[str, ...]

InstanceError

InstanceError(code: str, message: str)

Bases: ValueError

A refused match or resolution, with the code QVR uses for the same refusal.

PARAMETER DESCRIPTION
code

signature-mismatch, implicit-ambiguous, or implicit-missing.

TYPE: str

message

What was refused, naming the operation, the candidates, or the requirement.

TYPE: str

Source code in src/quivers/monadic/typeclasses.py
def __init__(self, code: str, message: str) -> None:
    self.code = code
    super().__init__(f"[{code}] {message}")

InstanceScope

InstanceScope(imports: tuple[InstanceScope, ...] = ())

Implicit instances, resolved as QVR resolves implicit module parameters.

A scope holds instances, each matched against its class when it is added, and rules that build an instance from other instances (the counterpart of an implicit functor). resolve is coherent (two solutions are an error, never a choice), tabled (a requirement met again while it is being solved has no solution along that path, so a rule that requires itself terminates), and scoped: a scope sees its own instances and those of the scopes it imports.

PARAMETER DESCRIPTION
imports

The scopes whose instances this one sees.

TYPE: tuple[InstanceScope, ...] DEFAULT: ()

Source code in src/quivers/monadic/typeclasses.py
def __init__(self, imports: tuple[InstanceScope, ...] = ()) -> None:
    self.imports = imports
    self._instances: list[
        tuple[str, Typeclass, Carrier, Functor | Foldable | MonadTrans]
    ] = []
    self._rules: list[
        tuple[
            str,
            Typeclass,
            Carrier,
            tuple[tuple[Typeclass, Carrier], ...],
            InstanceBuilder,
        ]
    ] = []

implicit

implicit(name: str, typeclass: Typeclass, carrier: Carrier, instance: Functor | Foldable | MonadTrans) -> None

Add an instance, after matching it against its class.

PARAMETER DESCRIPTION
name

The instance's name, used in diagnostics.

TYPE: str

typeclass

The class it is an instance of.

TYPE: Typeclass

carrier

What it is an instance at.

TYPE: Carrier

instance

The instance.

TYPE: Functor | Foldable | MonadTrans

RAISES DESCRIPTION
InstanceError

If the instance does not match the class.

Source code in src/quivers/monadic/typeclasses.py
def implicit(
    self,
    name: str,
    typeclass: Typeclass,
    carrier: Carrier,
    instance: Functor | Foldable | MonadTrans,
) -> None:
    """Add an instance, after matching it against its class.

    Parameters
    ----------
    name : str
        The instance's name, used in diagnostics.
    typeclass : Typeclass
        The class it is an instance of.
    carrier : Carrier
        What it is an instance at.
    instance : Functor | Foldable | MonadTrans
        The instance.

    Raises
    ------
    InstanceError
        If the instance does not match the class.
    """
    match_instance(instance, typeclass)
    self._instances.append((name, typeclass, carrier, instance))

implicit_rule

implicit_rule(name: str, typeclass: Typeclass, carrier: Carrier, requires: tuple[tuple[Typeclass, Carrier], ...], build: InstanceBuilder) -> None

Add a rule that builds an instance from the instances it requires.

PARAMETER DESCRIPTION
name

The rule's name, used in diagnostics.

TYPE: str

typeclass

The class of the instance it builds.

TYPE: Typeclass

carrier

What the built instance is an instance at.

TYPE: Carrier

requires

The requirements, resolved in the same scope.

TYPE: tuple[tuple[Typeclass, Carrier], ...]

build

Called with the resolved instances, in order.

TYPE: InstanceBuilder

Source code in src/quivers/monadic/typeclasses.py
def implicit_rule(
    self,
    name: str,
    typeclass: Typeclass,
    carrier: Carrier,
    requires: tuple[tuple[Typeclass, Carrier], ...],
    build: InstanceBuilder,
) -> None:
    """Add a rule that builds an instance from the instances it requires.

    Parameters
    ----------
    name : str
        The rule's name, used in diagnostics.
    typeclass : Typeclass
        The class of the instance it builds.
    carrier : Carrier
        What the built instance is an instance at.
    requires : tuple[tuple[Typeclass, Carrier], ...]
        The requirements, resolved in the same scope.
    build : InstanceBuilder
        Called with the resolved instances, in order.
    """
    self._rules.append((name, typeclass, carrier, requires, build))

resolve

resolve(typeclass: Typeclass, carrier: Carrier) -> Functor | Foldable | MonadTrans

The unique instance of a class at a carrier.

PARAMETER DESCRIPTION
typeclass

The class required.

TYPE: Typeclass

carrier

What the instance must be an instance at.

TYPE: Carrier

RETURNS DESCRIPTION
Functor | Foldable | MonadTrans

The instance; one of a class that extends typeclass also solves the requirement.

RAISES DESCRIPTION
InstanceError

With code implicit-ambiguous naming two solutions, or implicit-missing naming the requirement.

Source code in src/quivers/monadic/typeclasses.py
def resolve(
    self, typeclass: Typeclass, carrier: Carrier
) -> Functor | Foldable | MonadTrans:
    """The unique instance of a class at a carrier.

    Parameters
    ----------
    typeclass : Typeclass
        The class required.
    carrier : Carrier
        What the instance must be an instance at.

    Returns
    -------
    Functor | Foldable | MonadTrans
        The instance; one of a class that extends ``typeclass`` also
        solves the requirement.

    Raises
    ------
    InstanceError
        With code ``implicit-ambiguous`` naming two solutions, or
        ``implicit-missing`` naming the requirement.
    """
    return self._solve(typeclass, carrier, ())

signature_of

signature_of(typeclass: Typeclass) -> ClassSignature

The signature a typeclass states.

PARAMETER DESCRIPTION
typeclass

The class.

TYPE: Typeclass

RETURNS DESCRIPTION
ClassSignature

Its operations, the classes it extends, and its theory's laws.

Source code in src/quivers/monadic/typeclasses.py
def signature_of(typeclass: Typeclass) -> ClassSignature:
    """The signature a typeclass states.

    Parameters
    ----------
    typeclass : Typeclass
        The class.

    Returns
    -------
    ClassSignature
        Its operations, the classes it extends, and its theory's laws.
    """
    theory = _THEORIES.get(typeclass.__name__)
    laws: tuple[str, ...] = ()
    if theory is not None:
        closure: list[TypeclassTheory] = []
        pending = [theory]
        while pending:
            spec = pending.pop(0)
            if spec in closure:
                continue
            closure.append(spec)
            pending.extend(spec.extends)
        laws = tuple(
            dict.fromkeys(
                item.name for spec in reversed(closure) for item in spec.equations
            )
        )
    return ClassSignature(
        name=typeclass.__name__,
        operations=tuple(sorted(typeclass.__abstractmethods__)),
        extends=tuple(
            base.__name__
            for base in typeclass.__bases__
            if base is not ABC and issubclass(base, ABC)
        ),
        laws=laws,
    )

implements

implements(candidate: Functor | Foldable | MonadTrans, typeclass: Typeclass) -> bool

Whether an object matches a typeclass's signature.

PARAMETER DESCRIPTION
candidate

The object.

TYPE: Functor | Foldable | MonadTrans

typeclass

The class.

TYPE: Typeclass

RETURNS DESCRIPTION
bool

Whether it implements every operation the class states.

Source code in src/quivers/monadic/typeclasses.py
def implements(
    candidate: Functor | Foldable | MonadTrans, typeclass: Typeclass
) -> bool:
    """Whether an object matches a typeclass's signature.

    Parameters
    ----------
    candidate : Functor | Foldable | MonadTrans
        The object.
    typeclass : Typeclass
        The class.

    Returns
    -------
    bool
        Whether it implements every operation the class states.
    """
    return not missing_operations(candidate, typeclass)

missing_operations

missing_operations(candidate: Functor | Foldable | MonadTrans, typeclass: Typeclass) -> tuple[str, ...]

The operations of a class an object does not implement.

An operation is implemented when the object has a callable of that name that is not the class's own abstract declaration.

PARAMETER DESCRIPTION
candidate

The object.

TYPE: Functor | Foldable | MonadTrans

typeclass

The class.

TYPE: Typeclass

RETURNS DESCRIPTION
tuple[str, ...]

The missing operations, sorted.

Source code in src/quivers/monadic/typeclasses.py
def missing_operations(
    candidate: Functor | Foldable | MonadTrans, typeclass: Typeclass
) -> tuple[str, ...]:
    """The operations of a class an object does not implement.

    An operation is implemented when the object has a callable of that
    name that is not the class's own abstract declaration.

    Parameters
    ----------
    candidate : Functor | Foldable | MonadTrans
        The object.
    typeclass : Typeclass
        The class.

    Returns
    -------
    tuple[str, ...]
        The missing operations, sorted.
    """
    missing: list[str] = []
    for name in signature_of(typeclass).operations:
        implementation = getattr(type(candidate), name, None)
        if implementation is None or getattr(
            implementation, "__isabstractmethod__", False
        ):
            missing.append(name)
    return tuple(missing)

match_instance

match_instance(candidate: Functor | Foldable | MonadTrans, typeclass: Typeclass) -> ClassSignature

Check that an object matches a typeclass, as a module matches a signature.

PARAMETER DESCRIPTION
candidate

The object.

TYPE: Functor | Foldable | MonadTrans

typeclass

The class.

TYPE: Typeclass

RETURNS DESCRIPTION
ClassSignature

The class's signature, whose laws the instance now owes.

RAISES DESCRIPTION
InstanceError

With code signature-mismatch naming the first missing operation.

Source code in src/quivers/monadic/typeclasses.py
def match_instance(
    candidate: Functor | Foldable | MonadTrans, typeclass: Typeclass
) -> ClassSignature:
    """Check that an object matches a typeclass, as a module matches a signature.

    Parameters
    ----------
    candidate : Functor | Foldable | MonadTrans
        The object.
    typeclass : Typeclass
        The class.

    Returns
    -------
    ClassSignature
        The class's signature, whose laws the instance now owes.

    Raises
    ------
    InstanceError
        With code ``signature-mismatch`` naming the first missing
        operation.
    """
    missing = missing_operations(candidate, typeclass)
    if missing:
        raise InstanceError(
            "signature-mismatch",
            f"{type(candidate).__name__} does not match class {typeclass.__name__}: "
            f"it implements no operation {missing[0]!r}",
        )
    return signature_of(typeclass)

Package constants

The typeclass theories of quivers.monadic, each a TypeclassTheory.

Monadic structures: typeclass hierarchy, instances, algebraic effects, comonads, algebras, and distributive laws.

The Monad ABC lives in typeclasses. Concrete monad implementations (FuzzyPowersetMonad, GiryMonad, etc.) subclass it directly and provide the fmap_obj / fmap / pure / apply / join operations. unit and multiply are exposed as aliases on the concrete classes for the Eilenberg–Moore vocabulary.

UNIVERSE module-attribute

UNIVERSE = 'U'

The one sort of the combinatory encoding.

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.

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.

Conor McBride and Ross Paterson. Applicative programming with effects. Journal of Functional Programming, 18(1):1–13, 2008. URL: https://www.cambridge.org/core/journals/journal-of-functional-programming/article/applicative-programming-with-effects/C80616ACD5687ABDC86D2B341E83D298, doi:10.1017/S0956796807006326.