# Chapter 21  User defined equalities and relations

Claudio Sacerdoti Coen1

This chapter presents the extension of several equality related tactics to work over user-defined structures (called setoids) that are equipped with ad-hoc equivalence relations meant to behave as equalities. Actually, the tactics have also been generalized to relations weaker then equivalences (e.g. rewriting systems).

The work generalizes, and is partially based on, a previous implementation of the setoid_replace tactic by Clément Renard.

## 21.1  Relations and morphisms

A parametric relation R is any term of type forall (x1:T1) ...(xn:Tn), relation A. The expression A, which depends on x1 ...xn, is called the carrier of the relation and R is said to be a relation over A; the list x1,…,xn is the (possibly empty) list of parameters of the relation.

Example 1   It is possible to implement finite sets of elements of type A as unordered list of elements of type A. The function set_eq: forall (A: Type), relation (list A) satisfied by two lists with the same elements is a parametric relation over (list A) with one parameter A. The type of set_eq is convertible with forall (A: Type), list A -> list A -> Prop.

An instance of a parametric relation R with n parameters is any term (R t1 ...tn).

Let R be a relation over A with n parameters. A term is a parametric proof of reflexivity for R if it has type forall (x1:T1) ...(xn:Tn), reflexive (R x1 ...xn). Similar definitions are given for parametric proofs of symmetry and transitivity.

Example 2   The set_eq relation of the previous example can be proved to be reflexive, symmetric and transitive.

A parametric unary function f of type forall (x1:T1) ...(xn:Tn), A1 -> A2 covariantly respects two parametric relation instances R1 and R2 if, whenever m, n satisfy R1 x y, their images (f x) and (f y) satisfy R2 (f x) (f y) . An f that respects its input and output relations will be called a unary covariant morphism. We can also say that f is a monotone function with respect to R1 and R2. The sequence x1,… xn represents the parameters of the morphism.

Let R1 and R2 be two parametric relations. The signature of a parametric morphism of type forall (x1:T1) ...(xn:Tn), A1 -> A2 that covariantly respects two parametric relations that are instances of R1 and R2 is written R1 ++> R2. Notice that the special arrow ++>, which reminds the reader of covariance, is placed between the two parametric relations, not between the two carriers or the two relation instances.

The previous definitions are extended straightforwardly to n-ary morphisms, that are required to be simultaneously monotone on every argument.

Morphisms can also be contravariant in one or more of their arguments. A morphism is contravariant on an argument associated to the relation instance R if it is covariant on the same argument when the inverse relation R−1 is considered. The special arrow --> is used in signatures for contravariant morphisms.

Functions having arguments related by symmetric relations instances are both covariant and contravariant in those arguments. The special arrow ==> is used in signatures for morphisms that are both covariant and contravariant.

An instance of a parametric morphism f with n parameters is any term f t1 ...tn.

Example 3   Continuing the previous example, let union: forall (A: Type), list A -> list A -> list A perform the union of two sets by appending one list to the other. union is a binary morphism parametric over A that respects the relation instance (set_eq A). The latter condition is proved by showing forall (A: Type) (S1 S1' S2 S2': list A), set_eq A S1 S1' -> set_eq A S2 S2' -> set_eq A (union A S1 S2) (union A S1' S2').

The signature of the function union
is set_eq ==> set_eq ==> set_eq.

Example 4   The division function Rdiv: R -> R -> R is a morphism of signature le ++> le --> le where le is the usual order relation over real numbers. Notice that division is covariant in its first argument and contravariant in its second argument.

Notice that Leibniz equality is a relation and that every function is a morphism that respects Leibniz equality. Unfortunately, Leibniz equality is not always the intended equality for a given structure.

In the next section we will describe the commands to register terms as parametric relations and morphisms. Several tactics that deal with equality in Coq can also work with the registered relations. The exact list of tactic will be given in Sect. 21.7. For instance, the tactic reflexivity can be used to close a goal R n n whenever R is an instance of a registered reflexive relation. However, the tactics that replace in a context C[] one term with another one related by R must verify that C[] is a morphism that respects the intended relation. Currently the verification consists in checking whether C[] is a syntactic composition of morphism instances that respects some obvious compatibility constraints.

Example 5   Continuing the previous examples, suppose that the user must prove set_eq int (union int (union int S1 S2) S2) (f S1 S2) under the hypothesis H: set_eq int S2 (nil int). It is possible to use the rewrite tactic to replace the first two occurrences of S2 with nil int in the goal since the context set_eq int (union int (union int S1 nil) nil) (f S1 S2), being a composition of morphisms instances, is a morphism. However the tactic will fail replacing the third occurrence of S2 unless f has also been declared as a morphism.

## 21.2  Adding new relations and morphisms

A parametric relation Aeq: forall (x1:T1) ...(xn:Tn), relation (A x1 ...xn) over (A x1 ...xn) can be declared with the following command

[reflexivity proved by refl]
[symmetry proved by sym]
[transitivity proved by trans]
as id. after having required the Setoid module with the Require Setoid command.

The identifier id gives a unique name to the morphism and it is used by the command to generate fresh names for automatically provided lemmas used internally.

Notice that A is required to be a term having the same parameters of Aeq. This is a limitation of the tactic that is often unproblematic in practice.

The proofs of reflexivity, symmetry and transitivity can be omitted if the relation is not an equivalence relation.

If Aeq is a transitive relation, then the command also generates a lemma of type:
forall (x1:T1)...(xn:Tn) (x y x' y': (A x1 ...xn))
Aeq x
1 ...xn x' x -> Aeq x1 ...xn y y' ->
(Aeq x
1 ...xn x y -> Aeq x1 ...xn x' y')
that is used to declare Aeq as a parametric morphism of signature Aeq --> Aeq ++> impl where impl is logical implication seen as a parametric relation over Aeq.

Some tactics (reflexivity, symmetry, transitivity) work only on relations that respect the expected properties. The remaining tactics (replace, rewrite and derived tactics such as autorewrite) do not require any properties over the relation. However, they are able to replace terms with related ones only in contexts that are syntactic compositions of parametric morphism instances declared with the following command.

with signature sig
as id.
Proof
...
Qed

The command declares f as a parametric morphism of signature sig. The identifier id gives a unique name to the morphism and it is used by the command to generate fresh names for automatically provided lemmas used internally. The number of parameters for f is inferred by comparing its type with the provided signature. The command asks the user to prove interactively that f respects the relations identified from the signature.

Example 6   We start the example by assuming a small theory over homogeneous sets and we declare set equality as a parametric equivalence relation and union of two sets as a parametric morphism.
```
Require Export Relation_Definitions.
Require Export Setoid.
Set Implicit Arguments.
Set Contextual Implicit.
Parameter set: Type -> Type.
Parameter empty: forall A, set A.
Parameter eq_set: forall A, set A -> set A -> Prop.
Parameter union: forall A, set A -> set A -> set A.
Axiom eq_set_refl: forall A, reflexive _ (eq_set (A:=A)).
Axiom eq_set_sym: forall A, symmetric _ (eq_set (A:=A)).
Axiom eq_set_trans: forall A, transitive _ (eq_set (A:=A)).
Axiom empty_neutral: forall A (S: set A), eq_set (union S empty) S.
Axiom union_compat:
forall (A : Type),
forall x x' : set A, eq_set x x' ->
forall y y' : set A, eq_set y y' ->
eq_set (union x y) (union x' y').

reflexivity proved by (@eq_set_refl)
symmetry proved by (@eq_set_sym)
transitivity proved by (@eq_set_trans)
as eq_set_rel.

with signature eq_set ==> eq_set ==> eq_set
as union_mor.
Proof.
exact union_compat.
Qed.
```
We proceed now by proving a simple lemma performing a rewrite step and then applying reflexivity, as we would do working with Leibniz equality. Both tactic applications are accepted since the required properties over eq_set and union can be established from the two declarations above.
```
Goal forall (S: set nat),
eq_set (union (union S empty) S) (union S S).
Proof.
intros.
rewrite (@empty_neutral).
reflexivity.
Qed.
```

The tables of relations and morphisms are compatible with the Coq sectioning mechanism. If you declare a relation or a morphism inside a section, the declaration will be thrown away when closing the section. And when you load a compiled file, all the declarations of this file that were not inside a section will be loaded.

## 21.3  Rewriting and non reflexive relations

To replace only one argument of an n-ary morphism it is necessary to prove that all the other arguments are related to themselves by the respective relation instances.

Example 7   To replace (union S empty) with S in (union (union S empty) S) (union S S) the rewrite tactic must exploit the monotony of union (axiom union_compat in the previous example). Applying union_compat by hand we are left with the goal eq_set (union S S) (union S S).

When the relations associated to some arguments are not reflexive, the tactic cannot automatically prove the reflexivity goals, that are left to the user.

Setoids whose relation are partial equivalence relations (PER) are useful to deal with partial functions. Let R be a PER. We say that an element x is defined if R x x. A partial function whose domain comprises all the defined elements only is declared as a morphism that respects R. Every time a rewriting step is performed the user must prove that the argument of the morphism is defined.

Example 8   Let eqO be fun x y => x = y ∧  x≠ 0 (the smaller PER over non zero elements). Division can be declared as a morphism of signature eq ==> eq0 ==> eq. Replace x with y in div x n = div y n opens the additional goal eq0 n n that is equivalent to n=n ∧ n≠0.

## 21.4  Rewriting and non symmetric relations

When the user works up to relations that are not symmetric, it is no longer the case that any covariant morphism argument is also contravariant. As a result it is no longer possible to replace a term with a related one in every context, since the obtained goal implies the previous one if and only if the replacement has been performed in a contravariant position. In a similar way, replacement in an hypothesis can be performed only if the replaced term occurs in a covariant position.

Example 9   Suppose that division over real numbers has been defined as a morphism of signature Zdiv: Zlt ++> Zlt --> Zlt (i.e. Zdiv is increasing in its first argument, but decreasing on the second one). Let < denotes Zlt. Under the hypothesis H: x < y we have k < x / y -> k < x / x, but not k < y / x -> k < x / x. Dually, under the same hypothesis k < x / y -> k < y / y holds, but k < y / x -> k < y / y does not. Thus, if the current goal is k < x / x, it is possible to replace only the second occurrence of x (in contravariant position) with y since the obtained goal must imply the current one. On the contrary, if k < x / x is an hypothesis, it is possible to replace only the first occurrence of x (in covariant position) with y since the current hypothesis must imply the obtained one.

An error message will be raised by the rewrite and replace tactics when the user is trying to replace a term that occurs in the wrong position.

As expected, composing morphisms together propagates the variance annotations by switching the variance every time a contravariant position is traversed.
Example 10   Let us continue the previous example and let us consider the goal x / (x / x) < k. The first and third occurrences of x are in a contravariant position, while the second one is in covariant position. More in detail, the second occurrence of x occurs covariantly in (x / x) (since division is covariant in its first argument), and thus contravariantly in x / (x / x) (since division is contravariant in its second argument), and finally covariantly in x / (x / x) < k (since <, as every transitive relation, is contravariant in its first argument with respect to the relation itself).

## 21.5  Rewriting in ambiguous setoid contexts

One function can respect several different relations and thus it can be declared as a morphism having multiple signatures.

Example 11   Union over homogeneous lists can be given all the following signatures: eq ==> eq ==> eq (eq being the equality over ordered lists) set_eq ==> set_eq ==> set_eq (set_eq being the equality over unordered lists up to duplicates), multiset_eq ==> multiset_eq ==> multiset_eq (multiset_eq being the equality over unordered lists).

To declare multiple signatures for a morphism, repeat the Add Morphism command.

When morphisms have multiple signatures it can be the case that a rewrite request is ambiguous, since it is unclear what relations should be used to perform the rewriting. When non reflexive relations are involved, different choices lead to different sets of new goals to prove. In this case the tactic automatically picks one choice, but raises a warning describing the set of alternative new goals. To force one particular choice, the user can switch to the following alternative syntax for rewriting:

setoid_rewrite [orientation] term [in ident]
generate side conditions term1 ...termn
Up to the generate side conditions part, the syntax is equivalent to the one of the rewrite tactic. Additionally, the user can specify a list of new goals that the tactic must generate. The tactic will prune out from the alternative choices those choices that do not open at least the user proposed goals. Thus, providing enough side conditions, the user can restrict the tactic to at most one choice.

Example 12   Let [=]+ and [=]- be the smaller partial equivalence relations over positive (resp. negative) integers. Integer multiplication can be declared as a morphism with the following signatures: Zmult: Zlt ++> [=]+ ==> Zlt (multiplication with a positive number is increasing) and Zmult: Zlt --> [=]- ==> Zlt (multiplication with a negative number is decreasing). Given the hypothesis H: x < y and the goal (x * n) * m < 0 the tactic rewrite H proposes two alternative sets of goals that correspond to proving that n and m are both positive or both negative.
• ...⊢ (y * n) * m < 0
...⊢ n [=]+ n

...⊢ m [=]+ m

• ...⊢ (y * n) * m < 0
...⊢ n [=]- n

...⊢ m [=]- m
Remember that n [=]+ n is equivalent to n=n ∧ n > 0.

To pick the second set of goals it is sufficient to use setoid_rewrite H generate side conditions (m [=]- m)
since the side condition m [=]- m is contained only in the second set of goals.

## 21.6  First class setoids and morphisms

First class setoids and morphisms can also be handled by encoding them as records. The projections of the setoid relation and of the morphism function can be registered as parametric relations and morphisms, as illustrated by the following example.
Example 13
```
Require Export Relation_Definitions.
Require Setoid.

Record Setoid: Type :=
{ car:Type;
eq:car->car->Prop;
refl: reflexive _ eq;
sym: symmetric _ eq;
trans: transitive _ eq
}.

reflexivity proved by refl
symmetry proved by symm
transitivity proved by trans
as eq_rel.

Record Morphism (S1 S2:Setoid): Type :=
{ f:car S1 ->car S2;
compat: forall (x1 x2: car S1), eq S1 x1 x2 -> eq S2 (f x1) (f x2)
}.

Add Morphism f with signature eq ==> eq as apply_mor.
Proof.
intros S1 S2 m.
apply (compat S1 S2 m).
Qed.

Lemma test: forall (S1 S2:Setoid) (m: Morphism S1 S2)
(x y: car S1), eq S1 x y -> eq S2 (f _ _ m x) (f _ _ m y).
Proof.
intros.
rewrite H.
reflexivity.
Qed.
```

## 21.7  Tactics enabled on user provided relations

The following tactics, all prefixed by setoid_, deal with arbitrary registered relations and morphisms. Moreover, all the corresponding unprefixed tactics (i.e. reflexivity, symmetry, transitivity, replace, rewrite) have been extended to fall back to their prefixed counterparts when the relation involved is not Leibniz equality. Notice, however, that using the prefixed tactics it is possible to pass additional arguments such as generate side conditions or using relation.

setoid_reflexivity

setoid_symmetry [in ident]

setoid_transitivity

setoid_rewrite [orientation] term
[in ident]
[generate side conditions term1 ...termn]

The generate side conditions argument cannot be passed to the unprefixed form.

setoid_replace term with term  [in ident]
[using relation term]
[generate side conditions term1 ...termn]
[by tactic]

The generate side conditions and using relation arguments cannot be passed to the unprefixed form. The latter argument tells the tactic what parametric relation should be used to replace the first tactic argument with the second one. If omitted, it defaults to Leibniz equality.

Every derived tactic that is based on the unprefixed forms of the tactics considered above will also work up to user defined relations. For instance, it is possible to register hints for autorewrite that are not proof of Leibniz equalities. In particular it is possible to exploit autorewrite to simulate normalization in a term rewriting system up to user defined equalities.

## 21.8  Printing relations and morphisms

The Print Setoids command shows the list of currently registered parametric relations and morphisms. For each morphism its signature is also given. When the rewriting tactics refuse to replace a term in a context because the latter is not a composition of morphisms, the Print Setoids command is useful to understand what additional morphisms should be registered.

## 21.9  Deprecated syntax and backward incompatibilities

Due to backward compatibility reasons, the following syntax for the declaration of setoids and morphisms is also accepted.

Add Setoid A Aeq ST as ident where Aeq is a congruence relation without parameters, A is its carrier and ST is an object of type `(Setoid_Theory A Aeq)` (i.e. a record packing together the reflexivity, symmetry and transitivity lemmas). Notice that the syntax is not completely backward compatible since the identifier was not required.