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.
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 actionF : SetObject → SetObject.fmap— the morphism-level action sendingf : A → BtoF(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.
Applicative
¶
Bases: Functor, ABC
Applicative functor: pure + apply.
Adds:
pure— the unitη_A : A → F(A).apply— the application combinatorF(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
¶
apply
¶
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
lift_a2
¶
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
TYPE:
|
B
|
The factors and the codomain of
TYPE:
|
C
|
The factors and the codomain of
TYPE:
|
f
|
A function
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Morphism
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/monadic/typeclasses.py
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
¶
bind
¶
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:
|
B
|
The value types before and after the continuation.
TYPE:
|
k
|
The continuation
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Morphism
|
|
Source code in src/quivers/monadic/typeclasses.py
Alternative
¶
Bases: Applicative, ABC
Alternative: an Applicative with empty + alt.
Adds:
empty— the bottom element⊥_A : 1 → F(A).alt— pointwise alternativeF(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
¶
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.
Traversable
¶
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)
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)
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:
|
operations |
Every operation an instance must implement: the class's own abstract operations and those of every class it extends, sorted.
TYPE:
|
extends |
The classes it extends directly.
TYPE:
|
laws |
The laws of its theory (
TYPE:
|
InstanceError
¶
Bases: ValueError
A refused match or resolution, with the code QVR uses for the same refusal.
| PARAMETER | DESCRIPTION |
|---|---|
code
|
TYPE:
|
message
|
What was refused, naming the operation, the candidates, or the requirement.
TYPE:
|
Source code in src/quivers/monadic/typeclasses.py
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:
|
Source code in src/quivers/monadic/typeclasses.py
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:
|
typeclass
|
The class it is an instance of.
TYPE:
|
carrier
|
What it is an instance at.
TYPE:
|
instance
|
The instance.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
InstanceError
|
If the instance does not match the class. |
Source code in src/quivers/monadic/typeclasses.py
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:
|
typeclass
|
The class of the instance it builds.
TYPE:
|
carrier
|
What the built instance is an instance at.
TYPE:
|
requires
|
The requirements, resolved in the same scope. |
build
|
Called with the resolved instances, in order.
TYPE:
|
Source code in src/quivers/monadic/typeclasses.py
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:
|
carrier
|
What the instance must be an instance at.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Functor | Foldable | MonadTrans
|
The instance; one of a class that extends |
| RAISES | DESCRIPTION |
|---|---|
InstanceError
|
With code |
Source code in src/quivers/monadic/typeclasses.py
signature_of
¶
signature_of(typeclass: Typeclass) -> ClassSignature
The signature a typeclass states.
| PARAMETER | DESCRIPTION |
|---|---|
typeclass
|
The class.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ClassSignature
|
Its operations, the classes it extends, and its theory's laws. |
Source code in src/quivers/monadic/typeclasses.py
implements
¶
implements(candidate: Functor | Foldable | MonadTrans, typeclass: Typeclass) -> bool
Whether an object matches a typeclass's signature.
| PARAMETER | DESCRIPTION |
|---|---|
candidate
|
The object.
TYPE:
|
typeclass
|
The class.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether it implements every operation the class states. |
Source code in src/quivers/monadic/typeclasses.py
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:
|
typeclass
|
The class.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, ...]
|
The missing operations, sorted. |
Source code in src/quivers/monadic/typeclasses.py
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:
|
typeclass
|
The class.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ClassSignature
|
The class's signature, whose laws the instance now owes. |
| RAISES | DESCRIPTION |
|---|---|
InstanceError
|
With code |
Source code in src/quivers/monadic/typeclasses.py
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.
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.