Skip to content

Typeclass Laws

check_functor_laws and check_monad_laws test the identity and associativity laws of a type class instance on chosen objects (Moggi, 1991; Wadler, 1992). A passing check covers the values tested, and a proof that a law holds must cover the implementation's whole domain.

laws

Runtime checks of the functor and monad laws.

Each function takes a typeclass instance and a small set of representative objects or morphisms, then asserts that the relevant laws hold to within numerical tolerance by comparing the tensors of the two sides of each equation.

The same laws are equations of the theories in quivers.monadic.theories, stated there first-order over a universe of combinators, so a law is stated once as a Python predicate on tensors and once as a theory equation that panproto composes, transports along views, and checks in finite models.

References

LawCheck didactic-model

LawCheck(*, law: str, status: Literal['checked', 'assumed'], checked_at: tuple[str, ...] = ())

Bases: Model

How one law of a typeclass's theory fared on an instance.

ATTRIBUTE DESCRIPTION
law

The law's name in the class's theory (quivers.monadic.theories).

TYPE: str

status

checked when its tensor counterpart held, numerically, at the objects in checked_at (evidence at those objects, not a proof for every object); assumed when the law has no counterpart that the instance's operations evaluate (a law about the theory's combinators), so it is recorded rather than passed.

TYPE: Literal['checked', 'assumed']

checked_at

The objects a checked law was evaluated at.

TYPE: tuple[str, ...]

check_functor_laws

check_functor_laws(inst: Functor, A: SetObject, B: SetObject, C: SetObject, f: Morphism, g: Morphism) -> None

Assert the two functor laws hold for inst on the given data.

Laws:

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

The functor under test.

TYPE: Functor

A

The objects f and g connect.

TYPE: SetObject

B

The objects f and g connect.

TYPE: SetObject

C

The objects f and g connect.

TYPE: SetObject

f

A morphism A → B.

TYPE: Morphism

g

A morphism B → C.

TYPE: Morphism

RAISES DESCRIPTION
AssertionError

If either law fails.

Source code in src/quivers/monadic/laws.py
def check_functor_laws(
    inst: Functor, A: SetObject, B: SetObject, C: SetObject, f: Morphism, g: Morphism
) -> None:
    """Assert the two functor laws hold for ``inst`` on the given data.

    Laws:

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

    Parameters
    ----------
    inst : Functor
        The functor under test.
    A, B, C : SetObject
        The objects ``f`` and ``g`` connect.
    f : Morphism
        A morphism ``A → B``.
    g : Morphism
        A morphism ``B → C``.

    Raises
    ------
    AssertionError
        If either law fails.
    """
    fA = inst.fmap_obj(A)
    fid_lhs = inst.fmap(A, A, id_(A)).tensor
    fid_rhs = id_(fA).tensor
    assert _close(fid_lhs, fid_rhs), "Functor identity law violated"

    F_composed = inst.fmap(A, C, f >> g).tensor
    F_then = (inst.fmap(A, B, f) >> inst.fmap(B, C, g)).tensor
    assert _close(F_composed, F_then), "Functor composition law violated"

check_monad_laws

check_monad_laws(inst: Monad, A: SetObject) -> None

Assert the three monad laws hold for inst at A.

Laws, in terms of pure and join:

  • left unit: join_A ∘ pure_{F(A)} = id_{F(A)}
  • right unit: join_A ∘ F(pure_A) = id_{F(A)}
  • associativity: join_A ∘ F(join_A) = join_A ∘ join_{F(A)}

The check materializes F(F(F(A))), so A should be small for instances whose carrier grows quickly, such as function spaces.

PARAMETER DESCRIPTION
inst

The monad under test.

TYPE: Monad

A

The object at which the laws are checked.

TYPE: SetObject

RAISES DESCRIPTION
AssertionError

If any law fails.

Source code in src/quivers/monadic/laws.py
def check_monad_laws(inst: Monad, A: SetObject) -> None:
    """Assert the three monad laws hold for ``inst`` at ``A``.

    Laws, in terms of ``pure`` and ``join``:

    - left unit:     ``join_A ∘ pure_{F(A)} = id_{F(A)}``
    - right unit:    ``join_A ∘ F(pure_A) = id_{F(A)}``
    - associativity: ``join_A ∘ F(join_A) = join_A ∘ join_{F(A)}``

    The check materializes ``F(F(F(A)))``, so ``A`` should be small for
    instances whose carrier grows quickly, such as function spaces.

    Parameters
    ----------
    inst : Monad
        The monad under test.
    A : SetObject
        The object at which the laws are checked.

    Raises
    ------
    AssertionError
        If any law fails.
    """
    fA = inst.fmap_obj(A)
    ffA = inst.fmap_obj(fA)
    join_A = inst.join(A)
    id_fA = id_(fA).tensor

    left = (inst.pure(fA) >> join_A).tensor
    assert _close(left, id_fA), "Monad left unit law violated"

    right = (inst.fmap(A, fA, inst.pure(A)) >> join_A).tensor
    assert _close(right, id_fA), "Monad right unit law violated"

    inner_first = (inst.fmap(ffA, fA, join_A) >> join_A).tensor
    outer_first = (inst.join(fA) >> join_A).tensor
    assert _close(inner_first, outer_first), "Monad associativity law violated"

check_typeclass_laws

check_typeclass_laws(instance: Functor, typeclass: Typeclass, A: SetObject) -> tuple[LawCheck, ...]

Check an instance against every law of its class's theory, by name.

The laws are those of the class's theory and every theory it extends (signature_of(typeclass).laws). A law whose counterpart on tensors the instance's operations evaluate is checked at A: the functor identity and composition laws, and the monad unit and associativity laws in their join form. Every other law (the combinator and coherence equations of the theory) is recorded as assumed.

PARAMETER DESCRIPTION
instance

The instance.

TYPE: Functor

typeclass

The class it is an instance of.

TYPE: Typeclass

A

A small object the laws are checked at.

TYPE: SetObject

RETURNS DESCRIPTION
tuple[LawCheck, ...]

One record per law, in the theory's order.

RAISES DESCRIPTION
InstanceError

With code signature-mismatch naming the first law that fails.

Source code in src/quivers/monadic/laws.py
def check_typeclass_laws(
    instance: Functor, typeclass: Typeclass, A: SetObject
) -> tuple[LawCheck, ...]:
    """Check an instance against every law of its class's theory, by name.

    The laws are those of the class's theory and every theory it extends
    (`signature_of(typeclass).laws`). A law whose counterpart on tensors
    the instance's operations evaluate is checked at ``A``: the functor
    identity and composition laws, and the monad unit and associativity
    laws in their ``join`` form. Every other law (the combinator and
    coherence equations of the theory) is recorded as assumed.

    Parameters
    ----------
    instance : Functor
        The instance.
    typeclass : Typeclass
        The class it is an instance of.
    A : SetObject
        A small object the laws are checked at.

    Returns
    -------
    tuple[LawCheck, ...]
        One record per law, in the theory's order.

    Raises
    ------
    InstanceError
        With code ``signature-mismatch`` naming the first law that fails.
    """
    evaluations = _evaluations(instance, typeclass, A)
    checks: list[LawCheck] = []
    for law in signature_of(typeclass).laws:
        evaluate = evaluations.get(law)
        if evaluate is None:
            checks.append(LawCheck(law=law, status="assumed"))
            continue
        if not evaluate():
            raise InstanceError(
                "signature-mismatch",
                f"{type(instance).__name__} does not satisfy law {law!r} of class "
                f"{typeclass.__name__} at {A.name}",
            )
        checks.append(LawCheck(law=law, status="checked", checked_at=(str(A.name),)))
    return tuple(checks)

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.