Skip to content

Normalization by evaluation

Type-directed laws, eta for functions, surjective pairing for products, and the monad laws, are decided by evaluating a term into a semantic domain and reading it back at its type. The structures are recognized from the shapes of the declared laws (Equations and normalization §5).

nbe

Typed normalization by evaluation for type-directed laws.

Some laws are not oriented rules: eta for functions, surjective pairing, and the monad laws are type-directed, since whether t should become Lam(x. App(t, x)) depends on t's type. A theory whose laws include one of the structures below decides them by normalization by evaluation [@berger1991inverse]: a term is evaluated into a semantic domain and read back at its type, which yields the beta-eta-long normal form. Computations use Filinski's residualizing monad [@filinski2001normalization]: a computation is either a returned value or a neutral computation bound to a continuation, which validates the three monad laws and eta for the monad.

The structures are recognized from the declared laws, never from constructor names. Each law is matched against the schemas below with the constructors as unknowns, and a structure is used only when every one of its laws is declared, since normalizing with an undeclared law would identify terms the theory does not:

  • functions: beta A(L(x. M[x]), N) = M[N] and eta L(x. A(F, x)) = F;
  • products: P(Q(A, B)) = A, S(Q(A, B)) = B, and surjective pairing Q(P(X), S(X)) = X;
  • a monad: B(R(A), x. K[x]) = K[A], B(M, x. R(x)) = M, and B(B(M, x. K[x]), y. L[y]) = B(M, x. B(K[x], y. L[y])).

The type former of each structure is read from the typing judgment: the type its introduction form's typing rule concludes. Types come from a derivation of the term in that judgment, so the normalizer reads every constant at the type its occurrence was given.

OPAQUE_TYPE module-attribute

OPAQUE_TYPE = '?type'

The constructor an unsolved type variable is read as: an opaque base type.

SemanticComputation

SemanticComputation = Returned | Pending

The value of a term of computation type.

SemanticValue

A semantic value.

NormalizationError

Bases: ValueError

A term cannot be normalized by evaluation.

FunctionStructure didactic-model

FunctionStructure(*, lam: str, app: str, arrow: str = '')

Bases: Model

The constructors of a function type and its type former.

PARAMETER DESCRIPTION
lam

Abstraction and application.

TYPE: str

app

Abstraction and application.

TYPE: str

arrow

The function type former, or "" before it is read.

TYPE: str DEFAULT: ''

ProductStructure didactic-model

ProductStructure(*, pair: str, first: str, second: str, product: str = '')

Bases: Model

The constructors of a product type and its type former.

PARAMETER DESCRIPTION
pair

Pairing and the projections.

TYPE: str

first

Pairing and the projections.

TYPE: str

second

Pairing and the projections.

TYPE: str

product

The product type former, or "" before it is read.

TYPE: str DEFAULT: ''

MonadStructure didactic-model

MonadStructure(*, unit: str, bind: str, monad: str = '')

Bases: Model

The constructors of a monad and its type former.

PARAMETER DESCRIPTION
unit

The return and the bind of the monad.

TYPE: str

bind

The return and the bind of the monad.

TYPE: str

monad

The computation type former, or "" before it is read.

TYPE: str DEFAULT: ''

TypeDirectedStructure didactic-model

TypeDirectedStructure(*, function: FunctionStructure | None = None, product: ProductStructure | None = None, monad: MonadStructure | None = None, laws: tuple[str, ...] = ())

Bases: Model

The type-directed structures a theory's laws declare.

PARAMETER DESCRIPTION
function

Functions with beta and eta.

TYPE: FunctionStructure or None DEFAULT: None

product

Products with projections and surjective pairing.

TYPE: ProductStructure or None DEFAULT: None

monad

A monad with its three laws.

TYPE: MonadStructure or None DEFAULT: None

laws

The names of the laws the structures account for.

TYPE: tuple of str DEFAULT: ()

empty property

empty: bool

Whether no structure was found.

RETURNS DESCRIPTION
bool

True when there is nothing to normalize by evaluation.

Residual didactic-model

Residual(*, at: Callable[[int], Term] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Syntax as a function of the depth it is placed at (de Bruijn levels).

PARAMETER DESCRIPTION
at

The term at each depth.

TYPE: Callable[[int], Term] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

SemanticFunction didactic-model

SemanticFunction(*, apply: Callable[[SemanticValue], SemanticValue] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The value of a term of function type.

PARAMETER DESCRIPTION
apply

Application to a value.

TYPE: Callable DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

SemanticPair didactic-model

SemanticPair(*, first: SemanticValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY), second: SemanticValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The value of a term of product type.

PARAMETER DESCRIPTION
first

The components.

TYPE: SemanticValue DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

second

The components.

TYPE: SemanticValue DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

Returned didactic-model

Returned(*, value: SemanticValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A computation that returns a value.

PARAMETER DESCRIPTION
value

The value.

TYPE: SemanticValue DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

Pending didactic-model

Pending(*, computation: Residual = field(opaque=True, extras=OPAQUE_BY_IDENTITY), result: Term = field(opaque=True, extras=OPAQUE_BY_VALUE), then: Callable[[SemanticValue], SemanticComputation] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A neutral computation bound to a continuation: Filinski's residual bind.

PARAMETER DESCRIPTION
computation

The neutral computation.

TYPE: Residual DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

result

The type of the value it returns.

TYPE: Term DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

then

The rest of the computation, given that value.

TYPE: Callable DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

Normalizer

Normalizer(signature: Signature, structure: TypeDirectedStructure, system: JudgmentSystem, judgment: str)

Normalization by evaluation over a signature's typing judgment.

PARAMETER DESCRIPTION
signature

The signature.

TYPE: Signature

structure

The recognized structures with their type formers.

TYPE: TypeDirectedStructure

system

The judgments.

TYPE: JudgmentSystem

judgment

The typing judgment: a context, the scoped term, and one output type.

TYPE: str

RAISES DESCRIPTION
NormalizationError

If the judgment does not have that shape.

Source code in src/quivers/structural/theories/nbe.py
def __init__(
    self,
    signature: Signature,
    structure: TypeDirectedStructure,
    system: JudgmentSystem,
    judgment: str,
) -> None:
    form = system.forms.get(judgment)
    if form is None:
        raise NormalizationError(f"judgment {judgment!r} is not declared")
    modes = [a.mode for a in form.arguments]
    if (
        len(form.arguments) != 3
        or not form.arguments[0].context
        or modes != ["in", "in", "out"]
    ):
        raise NormalizationError(
            f"judgment {judgment!r} is not a typing judgment "
            "(ctx : Context[T] in, t : S in, ty : T out)"
        )
    self.signature = signature
    self.structure = structure
    self.system = system
    self.judgment = judgment
    roles: dict[str, str] = {}
    if structure.function is not None:
        roles[structure.function.lam] = "lam"
        roles[structure.function.app] = "app"
    if structure.product is not None:
        roles[structure.product.pair] = "pair"
        roles[structure.product.first] = "first"
        roles[structure.product.second] = "second"
    if structure.monad is not None:
        roles[structure.monad.unit] = "unit"
        roles[structure.monad.bind] = "bind"
    self.roles = roles

derive

derive(term: Term, context: Sequence[Term] = ()) -> tuple[Derivation, UnificationProblem]

The unique typing derivation of a term.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

context

The types of its free variables, outermost first.

TYPE: Sequence of Term DEFAULT: ()

RETURNS DESCRIPTION
tuple of Derivation and UnificationProblem

The derivation and the solution of its type variables.

RAISES DESCRIPTION
NormalizationError

If the term has no typing or more than one.

Source code in src/quivers/structural/theories/nbe.py
def derive(
    self, term: Term, context: Sequence[Term] = ()
) -> tuple[Derivation, UnificationProblem]:
    """The unique typing derivation of a term.

    Parameters
    ----------
    term : Term
        The term.
    context : Sequence of Term
        The types of its free variables, outermost first.

    Returns
    -------
    tuple of Derivation and UnificationProblem
        The derivation and the solution of its type variables.

    Raises
    ------
    NormalizationError
        If the term has no typing or more than one.
    """
    goal = self.system.goal(
        self.judgment,
        ContextValue(entries=tuple(from_term(t) for t in context)),
        term,
        None,
    )
    found = self.system.derivations(goal, limit=2)
    if len(found) > 1:
        raise NormalizationError(
            "normalization by evaluation needs a unique typing, and the "
            "term has several"
        )
    return next(iter(found))

normalize

normalize(term: Term, context: Sequence[Term] = ()) -> Term

The beta-eta-long normal form of a term at its principal type.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

context

The types of its free variables, outermost first.

TYPE: Sequence of Term DEFAULT: ()

RETURNS DESCRIPTION
Term

Its normal form.

Source code in src/quivers/structural/theories/nbe.py
def normalize(self, term: Term, context: Sequence[Term] = ()) -> Term:
    """The beta-eta-long normal form of a term at its principal type.

    Parameters
    ----------
    term : Term
        The term.
    context : Sequence of Term
        The types of its free variables, outermost first.

    Returns
    -------
    Term
        Its normal form.
    """
    derivation, problem = self.derive(term, context)
    type_ = self._type(derivation, problem)
    environment = tuple(
        self.reflect(_variable_at_level(level), t)
        for level, t in enumerate(context)
    )
    value = self.evaluate(derivation, problem, environment)
    return self.reify(value, type_, len(context))

equal_modulo

equal_modulo(left: Term, right: Term, context: Sequence[Term] = ()) -> bool

Whether two terms are equal modulo the type-directed laws.

Both are normalized at their unified principal type.

PARAMETER DESCRIPTION
left

The terms.

TYPE: Term

right

The terms.

TYPE: Term

context

The types of their free variables.

TYPE: Sequence of Term DEFAULT: ()

RETURNS DESCRIPTION
bool

True when their types unify and their normal forms agree.

Source code in src/quivers/structural/theories/nbe.py
def equal_modulo(
    self, left: Term, right: Term, context: Sequence[Term] = ()
) -> bool:
    """Whether two terms are equal modulo the type-directed laws.

    Both are normalized at their unified principal type.

    Parameters
    ----------
    left, right : Term
        The terms.
    context : Sequence of Term
        The types of their free variables.

    Returns
    -------
    bool
        ``True`` when their types unify and their normal forms agree.
    """
    one, one_problem = self.derive(left, context)
    two, two_problem = self.derive(right, context)
    left_type = one_problem.full(one.goal.arguments[2])
    right_type = two_problem.full(two.goal.arguments[2])
    problem = UnificationProblem(self.signature, {})
    if not problem.unify(left_type, right_type):
        return False
    common_type = problem.full(left_type)
    _require_data(common_type, self.signature)
    common = _ground(common_type)
    environment = tuple(
        self.reflect(_variable_at_level(level), t)
        for level, t in enumerate(context)
    )
    depth = len(context)
    return self.reify(
        self.evaluate(one, one_problem, environment), common, depth
    ) == self.reify(self.evaluate(two, two_problem, environment), common, depth)

evaluate

evaluate(derivation: Derivation, problem: UnificationProblem, environment: tuple[SemanticValue, ...]) -> SemanticValue

Evaluate a typed term into the semantic domain.

PARAMETER DESCRIPTION
derivation

The term's typing derivation, which follows its structure.

TYPE: Derivation

problem

The solution of its type variables.

TYPE: UnificationProblem

environment

The values of its free variables, outermost first.

TYPE: tuple of SemanticValue

RETURNS DESCRIPTION
SemanticValue

Its value.

RAISES DESCRIPTION
NormalizationError

If a non-structural constructor binds variables.

Source code in src/quivers/structural/theories/nbe.py
def evaluate(
    self,
    derivation: Derivation,
    problem: UnificationProblem,
    environment: tuple[SemanticValue, ...],
) -> SemanticValue:
    """Evaluate a typed term into the semantic domain.

    Parameters
    ----------
    derivation : Derivation
        The term's typing derivation, which follows its structure.
    problem : UnificationProblem
        The solution of its type variables.
    environment : tuple of SemanticValue
        The values of its free variables, outermost first.

    Returns
    -------
    SemanticValue
        Its value.

    Raises
    ------
    NormalizationError
        If a non-structural constructor binds variables.
    """
    term = derivation.goal.arguments[1]
    assert isinstance(term, Term)
    if term.op == BOUND_VAR:
        index = term.args[0]
        assert isinstance(index, int)
        return environment[-1 - index]
    role = self.roles.get(term.op)
    premises = [p for p in derivation.premises if p.goal.judgment == self.judgment]
    if role == "lam":
        (body,) = premises
        return SemanticFunction(
            apply=lambda value: self.evaluate(body, problem, (*environment, value))
        )
    if role == "app":
        function, argument = premises
        applied = self.evaluate(function, problem, environment)
        if not isinstance(applied, SemanticFunction):
            raise NormalizationError("an application of a non-function value")
        return applied.apply(self.evaluate(argument, problem, environment))
    if role == "pair":
        first, second = premises
        return SemanticPair(
            first=self.evaluate(first, problem, environment),
            second=self.evaluate(second, problem, environment),
        )
    if role in ("first", "second"):
        (pair,) = premises
        value = self.evaluate(pair, problem, environment)
        if not isinstance(value, SemanticPair):
            raise NormalizationError("a projection of a non-pair value")
        return value.first if role == "first" else value.second
    if role == "unit":
        (value,) = premises
        return Returned(value=self.evaluate(value, problem, environment))
    if role == "bind":
        computation, continuation = premises
        return _bind(
            self.evaluate(computation, problem, environment),
            lambda value: self.evaluate(
                continuation, problem, (*environment, value)
            ),
        )
    return self._neutral(term, derivation, problem, environment)

reify

reify(value: SemanticValue, type_: Term, depth: int) -> Term

Read a value back as a normal term at a type.

PARAMETER DESCRIPTION
value

The value.

TYPE: SemanticValue

type_

Its type.

TYPE: Term

depth

The number of variables in scope.

TYPE: int

RETURNS DESCRIPTION
Term

The beta-eta-long normal form.

RAISES DESCRIPTION
NormalizationError

If the value does not fit the type.

Source code in src/quivers/structural/theories/nbe.py
def reify(self, value: SemanticValue, type_: Term, depth: int) -> Term:
    """Read a value back as a normal term at a type.

    Parameters
    ----------
    value : SemanticValue
        The value.
    type_ : Term
        Its type.
    depth : int
        The number of variables in scope.

    Returns
    -------
    Term
        The beta-eta-long normal form.

    Raises
    ------
    NormalizationError
        If the value does not fit the type.
    """
    function = self.structure.function
    product = self.structure.product
    monad = self.structure.monad
    if function is not None and type_.op == function.arrow:
        domain, codomain = _two(type_)
        if not isinstance(value, SemanticFunction):
            raise NormalizationError("a function type holds a non-function value")
        argument = self.reflect(_variable_at_level(depth), domain)
        body = self.reify(value.apply(argument), codomain, depth + 1)
        return Term(op=function.lam, args=(body,))
    if product is not None and type_.op == product.product:
        left, right = _two(type_)
        if not isinstance(value, SemanticPair):
            raise NormalizationError("a product type holds a non-pair value")
        return Term(
            op=product.pair,
            args=(
                self.reify(value.first, left, depth),
                self.reify(value.second, right, depth),
            ),
        )
    if monad is not None and type_.op == monad.monad:
        (inner,) = type_.args
        assert isinstance(inner, Term)
        if isinstance(value, Returned):
            return Term(
                op=monad.unit, args=(self.reify(value.value, inner, depth),)
            )
        if isinstance(value, Pending):
            bound = self.reflect(_variable_at_level(depth), value.result)
            rest = value.then(bound)
            return Term(
                op=monad.bind,
                args=(
                    value.computation.at(depth),
                    self.reify(rest, type_, depth + 1),
                ),
            )
        raise NormalizationError("a computation type holds a non-computation value")
    if not isinstance(value, Residual):
        raise NormalizationError(
            f"a value of opaque type {type_.op!r} is not neutral"
        )
    return value.at(depth)

reflect

reflect(neutral: Residual, type_: Term) -> SemanticValue

Turn a neutral term into a value at a type, eta-expanding it.

PARAMETER DESCRIPTION
neutral

The neutral term.

TYPE: Residual

type_

Its type.

TYPE: Term

RETURNS DESCRIPTION
SemanticValue

Its value.

Source code in src/quivers/structural/theories/nbe.py
def reflect(self, neutral: Residual, type_: Term) -> SemanticValue:
    """Turn a neutral term into a value at a type, eta-expanding it.

    Parameters
    ----------
    neutral : Residual
        The neutral term.
    type_ : Term
        Its type.

    Returns
    -------
    SemanticValue
        Its value.
    """
    function = self.structure.function
    product = self.structure.product
    monad = self.structure.monad
    if function is not None and type_.op == function.arrow:
        domain, codomain = _two(type_)
        app = function.app

        def apply(argument: SemanticValue) -> SemanticValue:
            """Apply the neutral function to a value.

            Parameters
            ----------
            argument : SemanticValue
                The value.

            Returns
            -------
            SemanticValue
                The reflected application.
            """
            return self.reflect(
                Residual(
                    at=lambda depth: Term(
                        op=app,
                        args=(
                            neutral.at(depth),
                            self.reify(argument, domain, depth),
                        ),
                    )
                ),
                codomain,
            )

        return SemanticFunction(apply=apply)
    if product is not None and type_.op == product.product:
        left, right = _two(type_)
        first, second = product.first, product.second
        return SemanticPair(
            first=self.reflect(
                Residual(
                    at=lambda depth: Term(op=first, args=(neutral.at(depth),))
                ),
                left,
            ),
            second=self.reflect(
                Residual(
                    at=lambda depth: Term(op=second, args=(neutral.at(depth),))
                ),
                right,
            ),
        )
    if monad is not None and type_.op == monad.monad:
        (inner,) = type_.args
        assert isinstance(inner, Term)
        return Pending(computation=neutral, result=inner, then=_returned)
    return neutral

recognize

recognize(laws: Sequence[Equation]) -> TypeDirectedStructure

Find the complete type-directed structures among a theory's laws.

Each law is tried in both orientations against each schema. A structure is returned only when every one of its laws is present and all of them agree on the constructors.

PARAMETER DESCRIPTION
laws

The unoriented equations.

TYPE: Sequence of Equation

RETURNS DESCRIPTION
TypeDirectedStructure

The structures and the laws they account for.

Source code in src/quivers/structural/theories/nbe.py
def recognize(laws: Sequence[Equation]) -> TypeDirectedStructure:
    """Find the complete type-directed structures among a theory's laws.

    Each law is tried in both orientations against each schema. A
    structure is returned only when every one of its laws is present and
    all of them agree on the constructors.

    Parameters
    ----------
    laws : Sequence of Equation
        The unoriented equations.

    Returns
    -------
    TypeDirectedStructure
        The structures and the laws they account for.
    """
    found: dict[str, list[tuple[str, tuple[str, ...]]]] = {}

    def note(kind: str, law: str, roles: tuple[str, ...]) -> None:
        """Record a recognized law.

        Parameters
        ----------
        kind : str
            The schema.
        law : str
            The law's name.
        roles : tuple of str
            The constructors it fixes.
        """
        found.setdefault(kind, []).append((law, roles))

    for law in laws:
        for left, right in ((law.left, law.right), (law.right, law.left)):
            if (roles := _beta(left, right)) is not None:
                note("beta", law.name, roles)
            if (roles := _eta(left, right)) is not None:
                note("eta", law.name, roles)
            if (projection := _projection(left, right)) is not None:
                note(
                    f"proj{projection[2]}",
                    law.name,
                    (projection[0], projection[1]),
                )
            if (pairing := _surjective(left, right)) is not None:
                note("surjective", law.name, pairing)
            if (roles := _left_unit(left, right)) is not None:
                note("left_unit", law.name, roles)
            if (roles := _right_unit(left, right)) is not None:
                note("right_unit", law.name, roles)
            if (bind := _associative(left, right)) is not None:
                note("assoc", law.name, (bind,))
    used: list[str] = []
    function: FunctionStructure | None = None
    for beta_law, (lam, app) in found.get("beta", ()):
        for eta_law, roles in found.get("eta", ()):
            if roles == (lam, app):
                function = FunctionStructure(lam=lam, app=app)
                used += [beta_law, eta_law]
                break
        if function is not None:
            break
    product: ProductStructure | None = None
    for pair_law, (pair, first, second) in found.get("surjective", ()):
        first_law = next(
            (n for n, r in found.get("proj0", ()) if r == (first, pair)), None
        )
        second_law = next(
            (n for n, r in found.get("proj1", ()) if r == (second, pair)), None
        )
        if first_law is not None and second_law is not None:
            product = ProductStructure(pair=pair, first=first, second=second)
            used += [pair_law, first_law, second_law]
            break
    monad: MonadStructure | None = None
    for left_law, (unit, bind) in found.get("left_unit", ()):
        right_law = next(
            (n for n, r in found.get("right_unit", ()) if r == (unit, bind)), None
        )
        assoc_law = next((n for n, r in found.get("assoc", ()) if r == (bind,)), None)
        if right_law is not None and assoc_law is not None:
            monad = MonadStructure(unit=unit, bind=bind)
            used += [left_law, right_law, assoc_law]
            break
    return TypeDirectedStructure(
        function=function,
        product=product,
        monad=monad,
        laws=tuple(dict.fromkeys(used)),
    )

attach_types

attach_types(structure: TypeDirectedStructure, system: JudgmentSystem, judgment: str) -> TypeDirectedStructure

Read each structure's type former from the typing judgment's rules.

The type former of a structure is the head of the type the typing rule of its introduction form concludes: abstraction for functions, pairing for products, and return for the monad.

PARAMETER DESCRIPTION
structure

The recognized structure.

TYPE: TypeDirectedStructure

system

The judgments.

TYPE: JudgmentSystem

judgment

The typing judgment.

TYPE: str

RETURNS DESCRIPTION
TypeDirectedStructure

The structure with its type formers.

RAISES DESCRIPTION
NormalizationError

If an introduction form has no typing rule, or rules that conclude different type formers.

Source code in src/quivers/structural/theories/nbe.py
def attach_types(
    structure: TypeDirectedStructure, system: JudgmentSystem, judgment: str
) -> TypeDirectedStructure:
    """Read each structure's type former from the typing judgment's rules.

    The type former of a structure is the head of the type the typing rule
    of its introduction form concludes: abstraction for functions, pairing
    for products, and return for the monad.

    Parameters
    ----------
    structure : TypeDirectedStructure
        The recognized structure.
    system : JudgmentSystem
        The judgments.
    judgment : str
        The typing judgment.

    Returns
    -------
    TypeDirectedStructure
        The structure with its type formers.

    Raises
    ------
    NormalizationError
        If an introduction form has no typing rule, or rules that conclude
        different type formers.
    """

    def former(constructor: str) -> str:
        """The type former a constructor's typing rule concludes.

        Parameters
        ----------
        constructor : str
            The introduction form.

        Returns
        -------
        str
            The head of the concluded type.

        Raises
        ------
        NormalizationError
            If it is missing or ambiguous.
        """
        form = system.forms[judgment]
        scoped = system.scoped_position(form)
        outputs = [i for i, a in enumerate(form.arguments) if a.mode == "out"]
        heads: set[str] = set()
        for rule in system.rules:
            conclusion: Atom = rule.conclusion
            if conclusion.judgment != judgment or scoped is None:
                continue
            term = conclusion.arguments[scoped]
            if isinstance(term, VariablePattern) or not isinstance(
                term, PatternApplication
            ):
                continue
            if term.op != constructor:
                continue
            for position in outputs:
                value = conclusion.arguments[position]
                if isinstance(value, PatternApplication):
                    heads.add(value.op)
        if len(heads) != 1:
            raise NormalizationError(
                f"the typing rules of {constructor!r} in {judgment} conclude "
                f"{sorted(heads) or 'no type former'}; normalization by evaluation "
                "needs exactly one"
            )
        return heads.pop()

    return structure.with_(
        function=(
            structure.function.with_(arrow=former(structure.function.lam))
            if structure.function is not None
            else None
        ),
        product=(
            structure.product.with_(product=former(structure.product.pair))
            if structure.product is not None
            else None
        ),
        monad=(
            structure.monad.with_(monad=former(structure.monad.unit))
            if structure.monad is not None
            else None
        ),
    )