# Coq Reference Manual

# Chapter 2 Extensions of Gallina

- 2.1 Record types
- 2.2 Variants and extensions of match
- 2.3 Advanced recursive functions
- 2.4 Section mechanism
- 2.5 Module system
- 2.6 Libraries and qualified names
- 2.7 Implicit arguments
- 2.8 Coercions
- 2.9 Printing constructions in full
- 2.10 Printing universes
- 2.11 Existential variables

Gallina is the kernel language of Coq. We describe here extensions of the Gallina’s syntax.

## 2.1 Record types

The `Record` construction is a macro allowing the definition of records as is done in many programming languages. Its syntax is described on Figure 2.1. In fact, the `Record` macro is more general than the usual record types, since it allows also for “manifest” expressions. In this sense, the `Record` construction allows to define “signatures”.

> sentence | ++= | record
> record | ::= | record_keyword ident [binders] [: sort] `:=`
> |  | [ident] `{` [field ; … ; field] `}` `.`
> record_keyword | ::= | Record | Inductive | CoInductive
> field | ::= | name [binders] : type [ where notation ]
> | | | name [binders] [: term] := term

> Figure 2.1: Syntax for the definition of Record

In the expression

Record ident params : sort := ident0 `{` ident1 binders1 : term1; …identn bindersn : termn `}`.

the identifier ident is the name of the defined record and sort is its type. The identifier ident0 is the name of its constructor. If ident0 is omitted, the default name Build_ident is used. If sort is omitted, the default sort is “Type”. The identifiers ident1, .., identn are the names of fields and forall binders1, term1, ..., forall bindersn, termn their respective types. Remark that the type of identi may depend on the previous identj (for j<i). Thus the order of the fields is important. Finally, params are the parameters of the record.

More generally, a record may have explicitly defined (a.k.a. manifest) fields. For instance, Record ident [ params ] : sort := `{` ident1 : type1 `;` ident2 := term2 `;` ident3 : type3 `}` in which case the correctness of type3 may rely on the instance term2 of ident2 and term2 in turn may depend on ident1.

Example: The set of rational numbers may be defined as:

Coq < Record Rat : Set := mkRat
Coq < {sign : bool;
Coq < top : nat;
Coq < bottom : nat;
Coq < Rat_bottom_cond : 0 <> bottom;
Coq < Rat_irred_cond :
Coq < forall x y z:nat, (x * y) = top /\ (x * z) = bottom -> x = 1}.
Rat is defined
Rat_rect is defined
Rat_ind is defined
Rat_rec is defined
sign is defined
top is defined
bottom is defined
Rat_bottom_cond is defined
Rat_irred_cond is defined

Remark here that the field `Rat_cond` depends on the field `bottom`.

Let us now see the work done by the Record macro. First the macro generates an inductive definition with just one constructor:

> Inductive ident params :sort :=
> ident0 (ident1:term1) .. (identn:termn).

To build an object of type ident, one should provide the constructor ident0 with n terms filling the fields of the record.

As an example, let us define the rational 1/2:

Coq < Require Import Arith.
Coq < Theorem one_two_irred :
Coq < forall x y z:nat, x * y = 1 /\ x * z = 2 -> x = 1.

…

Coq < Qed.
Coq < Definition half := mkRat true 1 2 (O_S 1) one_two_irred.
half is defined
Coq < Check half.
half
: Rat

The macro generates also, when it is possible, the projection functions for destructuring an object of type ident. These projection functions have the same name that the corresponding fields. If a field is named “`_`” then no projection is built for it. In our example:

Coq < Eval compute in half.(top).
= 1
: nat
Coq < Eval compute in half.(bottom).
= 2
: nat
Coq < Eval compute in half.(Rat_bottom_cond).
= O_S 1
: 0 <> bottom half

Records defined with the Record keyword are not allowed to be recursive (references to the record’s name in the type of its field raises an error). To define recursive records, one can use the Inductive and CoInductive keywords, resulting in an inductive or co-inductive record. A caveat, however, is that records cannot appear in mutually inductive (or co-inductive) definitions.

Warnings:

1. Warning: identi cannot be defined.

   It can happen that the definition of a projection is impossible. This message is followed by an explanation of this impossibility. There may be three reasons:

   1. The name identi already exists in the environment (see Section 1.3.1).
   2. The body of identi uses an incorrect elimination for ident (see Sections 1.3.4 and 4.5.4).
   3. The type of the projections identi depends on previous projections which themselves could not be defined.

Error messages:

1. Records declared with the keyword Record or Structure cannot be recursive.

   The record name ident appears in the type of its fields, but uses the keyword Record. Use the keyword Inductive or CoInductive instead.

2. Cannot handle mutually (co)inductive records.

   Records cannot be defined as part of mutually inductive (or co-inductive) definitions, whether with records only or mixed with standard definitions.

3. During the definition of the one-constructor inductive definition, all the errors of inductive definitions, as described in Section 1.3.3, may also occur.

See also: Coercions and records in Section 18.9 of the chapter devoted to coercions.

Remark: Structure is a synonym of the keyword Record.

Remark: Creation of an object of record type can be done by calling ident0 and passing arguments in the correct order.

Coq < Record point := { x : nat; y : nat }.
point is defined
point_rect is defined
point_ind is defined
point_rec is defined
x is defined
y is defined
Coq < Definition a := Build_point 5 3.
a is defined

The following syntax allows to create objects by using named fields. The fields do not have to be in any particular order, nor do they have to be all present if the missing ones can be inferred or prompted for (see Section 23).

Coq < Definition b := {| x := 5; y := 3 |}.
b is defined
Coq < Definition c := {| y := 3; x := 5 |}.
c is defined

This syntax can be disabled globally for printing by

> Unset Printing Records.

For a given type, one can override this using either

> Add Printing Record ident.

to get record syntax or

> Add Printing Constructor ident.

to get constructor syntax.

This syntax can also be used for pattern matching.

Coq < Eval compute in (
Coq < match b with
Coq < | {| y := S n |} => n
Coq < | _ => 0
Coq < end).
= 2
: nat

Remark: An experimental syntax for projections based on a dot notation is available. The command to activate it is

> Set Printing Projections.

> term | ++= | term .( qualid )
> | | | term .( qualid arg … arg )
> | | | term .( @qualid term … term )

> Figure 2.2: Syntax of Record projections

The corresponding grammar rules are given Figure 2.2. When qualid denotes a projection, the syntax term.(qualid) is equivalent to qualid term, the syntax term.(qualid arg1 … argn) to qualid arg1 …argn term, and the syntax term.(@qualid term1 … termn) to @qualid term1 …termn term. In each case, term is the object projected and the other arguments are the parameters of the inductive type.

To deactivate the printing of projections, use Unset Printing Projections.

## 2.2 Variants and extensions of match

### 2.2.1 Multiple and nested pattern-matching

The basic version of `match` allows pattern-matching on simple patterns. As an extension, multiple nested patterns or disjunction of patterns are allowed, as in ML-like languages.

The extension just acts as a macro that is expanded during parsing into a sequence of match on simple patterns. Especially, a construction defined using the extended match is generally printed under its expanded form (see Set Printing Matching in section 2.2.4).

See also: Chapter 17.

### 2.2.2 Pattern-matching on boolean values: the if expression

For inductive types with exactly two constructors and for pattern-matchings expressions which do not depend on the arguments of the constructors, it is possible to use a if ... then ... else notation. For instance, the definition

Coq < Definition not (b:bool) :=
Coq < match b with
Coq < | true => false
Coq < | false => true
Coq < end.
not is defined

can be alternatively written

Coq < Definition not (b:bool) := if b then false else true.
not is defined

More generally, for an inductive type with constructors C1 and C2, we have the following equivalence

if term [dep_ret_type] then term1 else term2 ≡

match term [dep_ret_type] with
`|` C1 _ … _ `=>` term1
`|` C2 _ … _ `=>` term2
end

Here is an example.

Coq < Check (fun x (H:{x=0}+{x<>0}) =>
Coq < match H with
Coq < | left _ => true
Coq < | right _ => false
Coq < end).
fun (x : nat) (H : {x = 0} + {x <> 0}) => if H then true else false
: forall x : nat, {x = 0} + {x <> 0} -> bool

Notice that the printing uses the if syntax because sumbool is declared as such (see Section 2.2.4).

### 2.2.3 Irrefutable patterns: the destructuring let variants

Pattern-matching on terms inhabiting inductive type having only one constructor can be alternatively written using let ... in ... constructions. There are two variants of them.

#### First destructuring let syntax

The expression let ( ident1,…,identn ) := term0 in term1 performs case analysis on a term0 which must be in an inductive type with one constructor having itself n arguments. Variables ident1…identn are bound to the n arguments of the constructor in expression term1. For instance, the definition

Coq < Definition fst (A B:Set) (H:A * B) := match H with
Coq < | pair x y => x
Coq < end.
fst is defined

can be alternatively written

Coq < Definition fst (A B:Set) (p:A * B) := let (x, _) := p in x.
fst is defined

Notice that reduction is different from regular let ... in ... construction since it happens only if term0 is in constructor form. Otherwise, the reduction is blocked.

The pretty-printing of a definition by matching on a irrefutable pattern can either be done using match or the let construction (see Section 2.2.4).

If term inhabits an inductive type with one constructor C, we have an equivalence between

let (ident1,…,identn) [dep_ret_type] := term in term’

and

match term [dep_ret_type] with C ident1 … identn `=>` term’ end

#### Second destructuring let syntax

Another destructuring let syntax is available for inductive types with one constructor by giving an arbitrary pattern instead of just a tuple for all the arguments. For example, the preceding example can be written:

Coq < Definition fst (A B:Set) (p:A*B) := let ’pair x _ := p in x.
fst is defined

This is useful to match deeper inside tuples and also to use notations for the pattern, as the syntax let ’p := t in b allows arbitrary patterns to do the deconstruction. For example:

Coq < Definition deep_tuple (A:Set) (x:(A*A)*(A*A)) : A*A*A*A :=
Coq < let ’((a,b), (c, d)) := x in (a,b,c,d).
deep_tuple is defined
Coq < Notation " x ’with’ p " := (exist _ x p) (at level 20).
Coq < Definition proj1_sig’ (A:Set) (P:A->Prop) (t:{ x:A | P x }) : A :=
Coq < let ’x with p := t in x.
proj1_sig’ is defined

When printing definitions which are written using this construct it takes precedence over let printing directives for the datatype under consideration (see Section 2.2.4).

### 2.2.4 Controlling pretty-printing of match expressions

The following commands give some control over the pretty-printing of match expressions.

#### Printing nested patterns

The Calculus of Inductive Constructions knows pattern-matching only over simple patterns. It is however convenient to re-factorize nested pattern-matching into a single pattern-matching over a nested pattern. Coq’s printer try to do such limited re-factorization.

> Set Printing Matching.

This tells Coq to try to use nested patterns. This is the default behavior.

> Unset Printing Matching.

This tells Coq to print only simple pattern-matching problems in the same way as the Coq kernel handles them.

> Test Printing Matching.

This tells if the printing matching mode is on or off. The default is on.

#### Printing of wildcard pattern

Some variables in a pattern may not occur in the right-hand side of the pattern-matching clause. There are options to control the display of these variables.

> Set Printing Wildcard.

The variables having no occurrences in the right-hand side of the pattern-matching clause are just printed using the wildcard symbol “_”.

> Unset Printing Wildcard.

The variables, even useless, are printed using their usual name. But some non dependent variables have no name. These ones are still printed using a “_”.

> Test Printing Wildcard.

This tells if the wildcard printing mode is on or off. The default is to print wildcard for useless variables.

#### Printing of the elimination predicate

In most of the cases, the type of the result of a matched term is mechanically synthesizable. Especially, if the result type does not depend of the matched term.

> Set Printing Synth.

The result type is not printed when Coq knows that it can re-synthesize it.

> Unset Printing Synth.

This forces the result type to be always printed.

> Test Printing Synth.

This tells if the non-printing of synthesizable types is on or off. The default is to not print synthesizable types.

#### Printing matching on irrefutable pattern

If an inductive type has just one constructor, pattern-matching can be written using let ... := ... in ...

> Add Printing Let ident.

This adds ident to the list of inductive types for which pattern-matching is written using a let expression.

> Remove Printing Let ident.

This removes ident from this list.

> Test Printing Let for ident.

This tells if ident belongs to the list.

> Print Table Printing Let.

This prints the list of inductive types for which pattern-matching is written using a let expression.

The list of inductive types for which pattern-matching is written using a let expression is managed synchronously. This means that it is sensible to the command Reset.

#### Printing matching on booleans

If an inductive type is isomorphic to the boolean type, pattern-matching can be written using if ... then ... else ...

> Add Printing If ident.

This adds ident to the list of inductive types for which pattern-matching is written using an if expression.

> Remove Printing If ident.

This removes ident from this list.

> Test Printing If for ident.

This tells if ident belongs to the list.

> Print Table Printing If.

This prints the list of inductive types for which pattern-matching is written using an if expression.

The list of inductive types for which pattern-matching is written using an if expression is managed synchronously. This means that it is sensible to the command Reset.

#### Example

This example emphasizes what the printing options offer.

Coq < Test Printing Let for prod.
Cases on elements of prod are printed using a ‘let’ form
Coq < Print fst.
fst =
fun (A B : Set) (p : A * B) => let ’(x, _) := p in x
: forall A B : Set, A * B -> A
Argument scopes are [type_scope type_scope _]
Coq < Remove Printing Let prod.
Coq < Unset Printing Synth.
Coq < Unset Printing Wildcard.
Coq < Print fst.
fst =
fun (A B : Set) (p : A * B) => let ’(x, a) := p return A in x
: forall A B : Set, A * B -> A
Argument scopes are [type_scope type_scope _]

## 2.3 Advanced recursive functions

The experimental command

Function ident binder1…bindern {decrease_annot} : type0 := term0

can be seen as a generalization of Fixpoint. It is actually a wrapper for several ways of defining a function and other useful related objects, namely: an induction principle that reflects the recursive structure of the function (see 8.5.5), and its fixpoint equality. The meaning of this declaration is to define a function ident, similarly to Fixpoint. Like in Fixpoint, the decreasing argument must be given (unless the function is not recursive), but it must not necessary be structurally decreasing. The point of the {} annotation is to name the decreasing argument and to describe which kind of decreasing criteria must be used to ensure termination of recursive calls.

The Function construction enjoys also the with extension to define mutually recursive definitions. However, this feature does not work for non structural recursive functions.

See the documentation of functional induction (see Section 8.5.5) and Functional Scheme (see Section 13.2 and 13.2) for how to use the induction principle to easily reason about the function.

Remark: To obtain the right principle, it is better to put rigid parameters of the function as first arguments. For example it is better to define plus like this:

Coq < Function plus (m n : nat) {struct n} : nat :=
Coq < match n with
Coq < | 0 => m
Coq < | S p => S (plus m p)
Coq < end.

than like this:

Coq < Function plus (n m : nat) {struct n} : nat :=
Coq < match n with
Coq < | 0 => m
Coq < | S p => S (plus p m)
Coq < end.

##### Limitations

term0 must be build as a pure pattern-matching tree (match...with) with applications only at the end of each branch.

Function does not support partial application of the function being defined. Thus, the following example cannot be accepted due to the presence of partial application of identwrong into the body of identwrong :

Coq < Function wrong (C:nat) {\ldots} : nat :=
Coq < List.hd(List.map wrong (C::nil)).

For now dependent cases are not treated for non structurally terminating functions.

Error messages:

1. The recursive argument must be specified
2. No argument name ident
3. Cannot use mutual definition with well-founded recursion or measure
4. Cannot define graph for ident… (warning)

   The generation of the graph relation (R_ident) used to compute the induction scheme of ident raised a typing error. Only the ident is defined, the induction scheme will not be generated.

   This error happens generally when:

   - the definition uses pattern matching on dependent types, which Function cannot deal with yet.
   - the definition is not a pattern-matching tree as explained above.
5. Cannot define principle(s) for ident… (warning)

   The generation of the graph relation (R_ident) succeeded but the induction principle could not be built. Only the ident is defined. Please report.

6. Cannot build functional inversion principle (warning)

   functional inversion will not be available for the function.

See also: 13.2, 13.2, 8.5.5

Depending on the {…} annotation, different definition mechanisms are used by Function. More precise description given below.

Variants:

1. Function ident binder1…bindern : type0 := term0

   Defines the not recursive function ident as if declared with Definition. Moreover the following are defined:

   - ident_rect, ident_rec and ident_ind, which reflect the pattern matching structure of term0 (see the documentation of Inductive 1.3.3);
   - The inductive R_ident corresponding to the graph of ident (silently);
   - ident_complete and ident_correct which are inversion information linking the function and its graph.
2. Function ident binder1…bindern {struct ident0} : type0 := term0

   Defines the structural recursive function ident as if declared with Fixpoint. Moreover the following are defined:

   - The same objects as above;
   - The fixpoint equation of ident: ident_equation.
3. Function ident binder1…bindern {measure term1 ident0} : type0 := term0
4. Function ident binder1…bindern {wf term1 ident0} : type0 := term0

   Defines a recursive function by well founded recursion. The module Recdef of the standard library must be loaded for this feature. The {} annotation is mandatory and must be one of the following:

   - {measure term1 ident0} with ident0 being the decreasing argument and term1 being a function from type of ident0 to nat for which value on the decreasing argument decreases (for the lt order on nat) at each recursive call of term0, parameters of the function are bound in term0;
   - {wf term1 ident0} with ident0 being the decreasing argument and term1 an ordering relation on the type of ident0 (i.e. of type Tident0 → Tident0 → Prop) for which the decreasing argument decreases at each recursive call of term0. The order must be well founded. parameters of the function are bound in term0.

   Depending on the annotation, the user is left with some proof obligations that will be used to define the function. These proofs are: proofs that each recursive call is actually decreasing with respect to the given criteria, and (if the criteria is wf) a proof that the ordering relation is well founded.

   Once proof obligations are discharged, the following objects are defined:

   - The same objects as with the struct;
   - The lemma ident_tcc which collects all proof obligations in one property;
   - The lemmas ident_terminate and ident_F which is needed to be inlined during extraction of ident.

   The way this recursive function is defined is the subject of several papers by Yves Bertot and Antonia Balaa on the one hand, and Gilles Barthe, Julien Forest, David Pichardie, and Vlad Rusu on the other hand.

   Remark: Proof obligations are presented as several subgoals belonging to a Lemma ident_tcc.

## 2.4 Section mechanism

The sectioning mechanism allows to organize a proof in structured sections. Then local declarations become available (see Section 1.3.2).

### 2.4.1 Section ident

This command is used to open a section named ident.

### 2.4.2 End ident

This command closes the section named ident. After closing of the section, the local declarations (variables and local definitions) get discharged, meaning that they stop being visible and that all global objects defined in the section are generalized with respect to the variables and local definitions they each depended on in the section.

Here is an example :

Coq < Section s1.
Coq < Variables x y : nat.
x is assumed
y is assumed
Coq < Let y’ := y.
y’ is defined
Coq < Definition x’ := S x.
x’ is defined
Coq < Definition x’’ := x’ + y’.
x” is defined
Coq < Print x’.
x’ = S x
: nat
Coq < End s1.
Coq < Print x’.
x’ = fun x : nat => S x
: nat -> nat
Argument scope is [nat_scope]
Coq < Print x’’.
x” = fun x y : nat => let y’ := y in x’ x + y’
: nat -> nat -> nat
Argument scopes are [nat_scope nat_scope]

Notice the difference between the value of x’ and x’’ inside section s1 and outside.

Error messages:

1. This is not the last opened section

Remarks:

1. Most commands, like Hint, Notation, option management, ... which appear inside a section are canceled when the section is closed.

## 2.5 Module system

The module system provides a way of packaging related elements together, as well as a mean of massive abstraction.

> module_type | ::= | qualid
> | | | module_type with Definition qualid := term
> | | | module_type with Module qualid := qualid
> | | | qualid qualid … qualid
> | | | !qualid qualid … qualid
> module_binding | ::= | ( [Import|Export] ident … ident : module_type )
> module_bindings | ::= | module_binding … module_binding
> module_expression | ::= | qualid … qualid
> | | | !qualid … qualid

> Figure 2.3: Syntax of modules

In the syntax of module application, the ! prefix indicates that any Inline directive in the type of the functor arguments will be ignored (see 2.5.4 below).

### 2.5.1 Module ident

This command is used to start an interactive module named ident.

Variants:

1. Module ident module_bindings

   Starts an interactive functor with parameters given by module_bindings.

2. Module ident `:` module_type

   Starts an interactive module specifying its module type.

3. Module ident module_bindings `:` module_type

   Starts an interactive functor with parameters given by module_bindings, and output module type module_type.

4. Module ident `<:` module_type1 `<:` … `<:` module_typen

   Starts an interactive module satisfying each module_typei.

5. Module ident module_bindings `<:` module_type1 `<:` … `<:` module_typen

   Starts an interactive functor with parameters given by module_bindings. The output module type is verified against each module type module_typei.

6. Module [Import|Export]

   Behaves like Module, but automatically imports or exports the module.

#### Reserved commands inside an interactive module:

1. Include module

   Includes the content of module in the current interactive module. Here module can be a module expresssion or a module type expression. If module is a high-order module or module type expression then the system tries to instanciate module by the current interactive module.

2. Include module1 `<+` … `<+` modulen

   is a shortcut for Include module1 … Include modulen

### 2.5.2 End ident

This command closes the interactive module ident. If the module type was given the content of the module is matched against it and an error is signaled if the matching fails. If the module is basic (is not a functor) its components (constants, inductive types, submodules etc) are now available through the dot notation.

Error messages:

1. No such label ident
2. Signature components for label ident do not match
3. This is not the last opened module

### 2.5.3 Module ident := module_expression

This command defines the module identifier ident to be equal to module_expression.

Variants:

1. Module ident module_bindings := module_expression

   Defines a functor with parameters given by module_bindings and body module_expression.

2. Module ident module_bindings `:` module_type := module_expression

   Defines a functor with parameters given by module_bindings (possibly none), and output module type module_type, with body module_expression.

3. Module ident module_bindings `<:` module_type1 `<:` … `<:` module_typen:= module_expression

   Defines a functor with parameters given by module_bindings (possibly none) with body module_expression. The body is checked against each module_typei.

4. Module ident module_bindings := module_expression1 `<+` … `<+` module_expressionn

   is equivalent to an interactive module where each module_expressioni are included.

### 2.5.4 Module Type ident

This command is used to start an interactive module type ident.

Variants:

1. Module Type ident module_bindings

   Starts an interactive functor type with parameters given by module_bindings.

#### Reserved commands inside an interactive module type:

1. Include module

   Same as Include inside a module.

2. Include module1 `<+` … `<+` modulen

   is a shortcut for Include module1 … Include modulen

3. assumption_keyword Inline assums

   The instance of this assumption will be automatically expanded at functor application, except when this functor application is prefixed by a ! annotation.

### 2.5.5 End ident

This command closes the interactive module type ident.

Error messages:

1. This is not the last opened module type

### 2.5.6 Module Type ident := module_type

Defines a module type ident equal to module_type.

Variants:

1. Module Type ident module_bindings := module_type

   Defines a functor type ident specifying functors taking arguments module_bindings and returning module_type.

2. Module Type ident module_bindings := module_type1 `<+` … `<+` module_typen

   is equivalent to an interactive module type were each module_typei are included.

### 2.5.7 Declare Module ident : module_type

Declares a module ident of type module_type.

Variants:

1. Declare Module ident module_bindings `:` module_type

   Declares a functor with parameters module_bindings and output module type module_type.

#### Example

Let us define a simple module.

Coq < Module M.
Interactive Module M started
Coq < Definition T := nat.
T is defined
Coq < Definition x := 0.
x is defined
Coq < Definition y : bool.
1 subgoal
============================
bool
Coq < exact true.
No more subgoals.
Coq < Defined.
exact true.
y is defined
Coq < End M.
Module M is defined

Inside a module one can define constants, prove theorems and do any other things that can be done in the toplevel. Components of a closed module can be accessed using the dot notation:

Coq < Print M.x.
M.x = 0
: nat

A simple module type:

Coq < Module Type SIG.
Interactive Module Type SIG started
Coq < Parameter T : Set.
T is assumed
Coq < Parameter x : T.
x is assumed
Coq < End SIG.
Module Type SIG is defined

Now we can create a new module from M, giving it a less precise specification: the y component is dropped as well as the body of x.

Coq < Module N : SIG with Definition T := nat := M.
Coq < Coq < Module N is defined
Coq < Print N.T.
N.T = nat
: Set
Coq < Print N.x.
*** [ N.x : N.T ]
Coq < Print N.y.
Error: N.y not a defined object.

The definition of N using the module type expression SIG with Definition T:=nat is equivalent to the following one:

Coq < Module Type SIG’.
Coq < Definition T : Set := nat.
Coq < Parameter x : T.
Coq < End SIG’.
Coq < Module N : SIG’ := M.

If we just want to be sure that the our implementation satisfies a given module type without restricting the interface, we can use a transparent constraint

Coq < Module P <: SIG := M.
Module P is defined
Coq < Print P.y.
P.y = true
: bool

Now let us create a functor, i.e. a parametric module

Coq < Module Two (X Y: SIG).
Interactive Module Two started
Coq < Definition T := (X.T * Y.T)%type.
Coq < Definition x := (X.x, Y.x).
Coq < End Two.
Module Two is defined

and apply it to our modules and do some computations

Coq < Module Q := Two M N.
Module Q is defined
Coq < Eval compute in (fst Q.x + snd Q.x).
= N.x
: nat

In the end, let us define a module type with two sub-modules, sharing some of the fields and give one of its possible implementations:

Coq < Module Type SIG2.
Interactive Module Type SIG2 started
Coq < Declare Module M1 : SIG.
Module M1 is declared
Coq < Module M2 <: SIG.
Interactive Module M2 started
Coq < Definition T := M1.T.
T is defined
Coq < Parameter x : T.
x is assumed
Coq < End M2.
Module M2 is defined
Coq < End SIG2.
Module Type SIG2 is defined
Coq < Module Mod <: SIG2.
Coq < Module M1.
Coq < Definition T := nat.
Coq < Definition x := 1.
Coq < End M1.
Coq < Module M2 := M.
Coq < End Mod.
Module Mod is defined

Notice that M is a correct body for the component M2 since its T component is equal nat and hence M1.T as specified.

Remarks:

1. Modules and module types can be nested components of each other.
2. One can have sections inside a module or a module type, but not a module or a module type inside a section.
3. Commands like Hint or Notation can also appear inside modules and module types. Note that in case of a module definition like:

   Module N : SIG := M.

   or

   Module N : SIG.
   …
   End N.

   hints and the like valid for N are not those defined in M (or the module body) but the ones defined in SIG.

### 2.5.8 Import qualid

If qualid denotes a valid basic module (i.e. its module type is a signature), makes its components available by their short names.

Example:

Coq < Module Mod.
Interactive Module Mod started
Coq < Definition T:=nat.
T is defined
Coq < Check T.
T
: Set
Coq < End Mod.
Module Mod is defined
Coq < Check Mod.T.
Mod.T
: Set
Coq < Check T. (* Incorrect ! *)
Toplevel input, characters 6-7:
> Check T.
> ^
Error: The reference T was not found in the current environment.
Coq < Import Mod.
Coq < Check T. (* Now correct *)
T
: Set

Some features defined in modules are activated only when a module is imported. This is for instance the case of notations (see Section 12.1).

Variants:

1. Export qualid

   When the module containing the command Export qualid is imported, qualid is imported as well.

Error messages:

1. qualid is not a module

Warnings:

1. Warning: Trying to mask the absolute name qualid !

### 2.5.9 Print Module ident

Prints the module type and (optionally) the body of the module ident.

### 2.5.10 Print Module Type ident

Prints the module type corresponding to ident.

### 2.5.11 Locate Module qualid

Prints the full name of the module qualid.

## 2.6 Libraries and qualified names

### 2.6.1 Names of libraries and files

##### Libraries

The theories developed in Coq are stored in library files which are hierarchically classified into libraries and sublibraries. To express this hierarchy, library names are represented by qualified identifiers qualid, i.e. as list of identifiers separated by dots (see Section 1.2.3). For instance, the library file Mult of the standard Coq library Arith has name Coq.Arith.Mult. The identifier that starts the name of a library is called a library root. All library files of the standard library of Coq have reserved root Coq but library file names based on other roots can be obtained by using coqc options -I or -R (see Section 14.4.1). Also, when an interactive Coq session starts, a library of root Top is started, unless option -top or -notop is set (see Section 14.4.1).

As library files are stored on the file system of the underlying operating system, a translation from file-system names to Coq names is needed. In this translation, names in the file system are called physical paths while Coq names are contrastingly called logical names. Logical names are mapped to physical paths using the commands Add LoadPath or Add Rec LoadPath (see Sections 6.6.3 and 6.6.4).

### 2.6.2 Qualified names

Library files are modules which possibly contain submodules which eventually contain constructions (axioms, parameters, definitions, lemmas, theorems, remarks or facts). The absolute name, or full name, of a construction in some library file is a qualified identifier starting with the logical name of the library file, followed by the sequence of submodules names encapsulating the construction and ended by the proper name of the construction. Typically, the absolute name Coq.Init.Logic.eq denotes Leibniz’ equality defined in the module Logic in the sublibrary Init of the standard library of Coq.

The proper name that ends the name of a construction is the short name (or sometimes base name) of the construction (for instance, the short name of Coq.Init.Logic.eq is eq). Any partial suffix of the absolute name is a partially qualified name (e.g. Logic.eq is a partially qualified name for Coq.Init.Logic.eq). Especially, the short name of a construction is its shortest partially qualified name.

Coq does not accept two constructions (definition, theorem, ...) with the same absolute name but different constructions can have the same short name (or even same partially qualified names as soon as the full names are different).

Notice that the notion of absolute, partially qualified and short names also applies to library file names.

##### Visibility

Coq maintains a table called name table which maps partially qualified names of constructions to absolute names. This table is updated by the commands Require (see 6.5.1), Import and Export (see 2.5.8) and also each time a new declaration is added to the context. An absolute name is called visible from a given short or partially qualified name when this latter name is enough to denote it. This means that the short or partially qualified name is mapped to the absolute name in Coq name table.

A similar table exists for library file names. It is updated by the vernacular commands Add LoadPath and Add Rec LoadPath (or their equivalent as options of the Coq executables, -I and -R).

It may happen that a visible name is hidden by the short name or a qualified name of another construction. In this case, the name that has been hidden must be referred to using one more level of qualification. To ensure that a construction always remains accessible, absolute names can never be hidden.

Examples:

Coq < Check 0.
0
: nat
Coq < Definition nat := bool.
nat is defined
Coq < Check 0.
0
: Datatypes.nat
Coq < Check Datatypes.nat.
Datatypes.nat
: Set
Coq < Locate nat.
Constant Top.nat
Inductive Coq.Init.Datatypes.nat
(shorter name to refer to it in current context is Datatypes.nat)

See also: Command Locate in Section 6.3.10 and Locate Library in Section 6.6.11.

## 2.7 Implicit arguments

An implicit argument of a function is an argument which can be inferred from contextual knowledge. There are different kinds of implicit arguments that can be considered implicit in different ways. There are also various commands to control the setting or the inference of implicit arguments.

### 2.7.1 The different kinds of implicit arguments

#### Implicit arguments inferable from the knowledge of other arguments of a function

The first kind of implicit arguments covers the arguments that are inferable from the knowledge of the type of other arguments of the function, or of the type of the surrounding context of the application. Especially, such implicit arguments correspond to parameters dependent in the type of the function. Typical implicit arguments are the type arguments in polymorphic functions. There are several kinds of such implicit arguments.

##### Strict Implicit Arguments.

An implicit argument can be either strict or non strict. An implicit argument is said strict if, whatever the other arguments of the function are, it is still inferable from the type of some other argument. Technically, an implicit argument is strict if it corresponds to a parameter which is not applied to a variable which itself is another parameter of the function (since this parameter may erase its arguments), not in the body of a match, and not itself applied or matched against patterns (since the original form of the argument can be lost by reduction).

For instance, the first argument of

> `cons: forall A:Set, A -> list A -> list A`

in module List.v is strict because list is an inductive type and A will always be inferable from the type list A of the third argument of cons. On the contrary, the second argument of a term of type

> `forall P:nat->Prop, forall n:nat, P n -> ex nat P`

is implicit but not strict, since it can only be inferred from the type P n of the third argument and if P is, e.g., fun _ => True, it reduces to an expression where n does not occur any longer. The first argument P is implicit but not strict either because it can only be inferred from P n and P is not canonically inferable from an arbitrary n and the normal form of P n (consider e.g. that n is 0 and the third argument has type True, then any P of the form fun n => match n with 0 => True | _ => anything end would be a solution of the inference problem).

##### Contextual Implicit Arguments.

An implicit argument can be contextual or not. An implicit argument is said contextual if it can be inferred only from the knowledge of the type of the context of the current expression. For instance, the only argument of

> `nil : forall A:Set, list A`

is contextual. Similarly, both arguments of a term of type

> `forall P:nat->Prop, forall n:nat, P n \/ n = 0`

are contextual (moreover, n is strict and P is not).

##### Reversible-Pattern Implicit Arguments.

There is another class of implicit arguments that can be reinferred unambiguously if all the types of the remaining arguments are known. This is the class of implicit arguments occurring in the type of another argument in position of reversible pattern, which means it is at the head of an application but applied only to uninstantiated distinct variables. Such an implicit argument is called reversible-pattern implicit argument. A typical example is the argument P of nat_rec in

> nat_rec : forall P : nat -> Set, P 0 -> (forall n : nat, P n -> P (S n)) -> forall x : nat, P x.

(P is reinferable by abstracting over n in the type P n).

See Section 2.7.9 for the automatic declaration of reversible-pattern implicit arguments.

#### Implicit arguments inferable by resolution

This corresponds to a class of non dependent implicit arguments that are solved based on the structure of their type only.

### 2.7.2 Maximal or non maximal insertion of implicit arguments

In case a function is partially applied, and the next argument to be applied is an implicit argument, two disciplines are applicable. In the first case, the function is considered to have no arguments furtherly: one says that the implicit argument is not maximally inserted. In the second case, the function is considered to be implicitly applied to the implicit arguments it is waiting for: one says that the implicit argument is maximally inserted.

Each implicit argument can be declared to have to be inserted maximally or non maximally. This can be governed argument per argument by the command Implicit Arguments (see 2.7.4) or globally by the command Set Maximal Implicit Insertion (see 2.7.10). See also Section 2.7.14.

### 2.7.3 Casual use of implicit arguments

In a given expression, if it is clear that some argument of a function can be inferred from the type of the other arguments, the user can force the given argument to be guessed by replacing it by “_”. If possible, the correct argument will be automatically generated.

Error messages:

1. Cannot infer a term for this placeholder

   Coq was not able to deduce an instantiation of a “_”.

### 2.7.4 Declaration of implicit arguments for a constant

In case one wants that some arguments of a given object (constant, inductive types, constructors, assumptions, local or not) are always inferred by Coq, one may declare once and for all which are the expected implicit arguments of this object. There are two ways to do this, a priori and a posteriori.

#### Implicit Argument Binders

In the first setting, one wants to explicitly give the implicit arguments of a constant as part of its definition. To do this, one has to surround the bindings of implicit arguments by curly braces:

Coq < Definition id {A : Type} (x : A) : A := x.
id is defined

This automatically declares the argument A of id as a maximally inserted implicit argument. One can then do as-if the argument was absent in every situation but still be able to specify it if needed:

Coq < Definition compose {A B C} (g : B -> C) (f : A -> B) :=
Coq < fun x => g (f x).
compose is defined
Coq < Goal forall A, compose id id = id (A:=A).
1 subgoal
============================
forall A : Type, compose id id = id

The syntax is supported in all top-level definitions: Definition, Fixpoint, Lemma and so on. For (co-)inductive datatype declarations, the semantics are the following: an inductive parameter declared as an implicit argument need not be repeated in the inductive definition but will become implicit for the constructors of the inductive only, not the inductive type itself. For example:

Coq < Inductive list {A : Type} : Type :=
Coq < | nil : list
Coq < | cons : A -> list -> list.
list is defined
list_rect is defined
list_ind is defined
list_rec is defined
Coq < Print list.
Inductive list (A : Type) : Type := nil : list | cons : A -> list -> list
For list: Argument A is implicit and maximally inserted
For nil: Argument A is implicit and maximally inserted
For cons: Argument A is implicit and maximally inserted
For list: Argument scope is [type_scope]
For nil: Argument scope is [type_scope]
For cons: Argument scopes are [type_scope _ _]

One can always specify the parameter if it is not uniform using the usual implicit arguments disambiguation syntax.

#### Declaring Implicit Arguments

To set implicit arguments for a constant a posteriori, one can use the command:

> Arguments qualid possibly_bracketed_ident … possibly_bracketed_ident

where the list of possibly_bracketed_ident is the list of all arguments of qualid where the ones to be declared implicit are surrounded by square brackets and the ones to be declared as maximally inserted implicits are surrounded by curly braces.

After the above declaration is issued, implicit arguments can just (and have to) be skipped in any expression involving an application of qualid.

Variants:

1. Global Arguments qualid possibly_bracketed_ident … possibly_bracketed_ident

   Tell to recompute the implicit arguments of qualid after ending of the current section if any, enforcing the implicit arguments known from inside the section to be the ones declared by the command.

2. Local Arguments qualid possibly_bracketed_ident … possibly_bracketed_ident

   When in a module, tell not to activate the implicit arguments of qualid declared by this command to contexts that require the module.

3. [Global | Local] Arguments qualid [possibly_bracketed_ident … possibly_bracketed_ident , … , possibly_bracketed_ident … possibly_bracketed_ident]

   For names of constants, inductive types, constructors, lemmas which can only be applied to a fixed number of arguments (this excludes for instance constants whose type is polymorphic), multiple implicit arguments decflarations can be given. Depending on the number of arguments qualid is applied to in practice, the longest applicable list of implicit arguments is used to select which implicit arguments are inserted.

   For printing, the omitted arguments are the ones of the longest list of implicit arguments of the sequence.

Example:

Coq < Inductive list (A:Type) : Type :=
Coq < | nil : list A
Coq < | cons : A -> list A -> list A.
Coq < Check (cons nat 3 (nil nat)).
cons nat 3 (nil nat)
: list nat
Coq < Arguments cons [A] _ _.
Coq < Arguments nil [A].
Coq < Check (cons 3 nil).
cons 3 nil
: list nat
Coq < Fixpoint map (A B:Type) (f:A->B) (l:list A) : list B :=
Coq < match l with nil => nil | cons a t => cons (f a) (map A B f t) end.
map is recursively defined (decreasing on 4th argument)
Coq < Fixpoint length (A:Type) (l:list A) : nat :=
Coq < match l with nil => 0 | cons _ m => S (length A m) end.
length is recursively defined (decreasing on 2nd argument)
Coq < Arguments map [A B] f l.
Coq < Arguments length {A} l. (* A has to be maximally inserted *)
Coq < Check (fun l:list (list nat) => map length l).
fun l : list (list nat) => map length l
: list (list nat) -> list nat
Coq < Arguments map [A B] f l, [A] B f l, A B f l.
Coq < Check (fun l => map length l = map (list nat) nat length l).
fun l : list (list nat) => map length l = map length l
: list (list nat) -> Prop

Remark: To know which are the implicit arguments of an object, use the command Print Implicit (see 2.7.14).

Remark: If the list of arguments is empty, the command removes the implicit arguments of qualid.

### 2.7.5 Automatic declaration of implicit arguments for a constant

Coq can also automatically detect what are the implicit arguments of a defined object. The command is just

> Arguments qualid : default implicits

The auto-detection is governed by options telling if strict, contextual, or reversible-pattern implicit arguments must be considered or not (see Sections 2.7.7, 2.7.8, 2.7.9 and also 2.7.10).

Variants:

1. Global Arguments qualid : default implicits

   Tell to recompute the implicit arguments of qualid after ending of the current section if any.

2. Local Arguments qualid : default implicits

   When in a module, tell not to activate the implicit arguments of qualid computed by this declaration to contexts that requires the module.

Example:

Coq < Inductive list (A:Set) : Set :=
Coq < | nil : list A
Coq < | cons : A -> list A -> list A.
Coq < Arguments cons : default implicits.
Coq < Print Implicit cons.
cons : forall A : Set, A -> list A -> list A
Argument A is implicit
Coq < Arguments nil : default implicits.
Coq < Print Implicit nil.
nil : forall A : Set, list A
Coq < Set Contextual Implicit.
Coq < Arguments nil : default implicits.
Coq < Print Implicit nil.
nil : forall A : Set, list A
Argument A is implicit and maximally inserted

The computation of implicit arguments takes account of the unfolding of constants. For instance, the variable p below has type (Transitivity R) which is reducible to forall x,y:U, R x y -> forall z:U, R y z -> R x z. As the variables x, y and z appear strictly in body of the type, they are implicit.

Coq < Variable X : Type.
Coq < Definition Relation := X -> X -> Prop.
Coq < Definition Transitivity (R:Relation) :=
Coq < forall x y:X, R x y -> forall z:X, R y z -> R x z.
Coq < Variables (R : Relation) (p : Transitivity R).
Coq < Arguments p : default implicits.
Coq < Print p.
*** [ p : Transitivity R ]
Expanded type for implicit arguments
p : forall x y : X, R x y -> forall z : X, R y z -> R x z
Arguments x, y, z are implicit
Coq < Print Implicit p.
p : forall x y : X, R x y -> forall z : X, R y z -> R x z
Arguments x, y, z are implicit
Coq < Variables (a b c : X) (r1 : R a b) (r2 : R b c).
Coq < Check (p r1 r2).
p r1 r2
: R a c

Implicit arguments can be cleared with the following syntax:

> Arguments qualid : clear implicits

In the following example implict arguments declarations for the nil constant are cleared:

Coq < Arguments cons : clear implicits.
Coq < Print Implicit cons.
cons : forall A : Set, A -> list A -> list A

### 2.7.6 Mode for automatic declaration of implicit arguments

In case one wants to systematically declare implicit the arguments detectable as such, one may switch to the automatic declaration of implicit arguments mode by using the command

> Set Implicit Arguments.

Conversely, one may unset the mode by using Unset Implicit Arguments. The mode is off by default. Auto-detection of implicit arguments is governed by options controlling whether strict and contextual implicit arguments have to be considered or not.

### 2.7.7 Controlling strict implicit arguments

When the mode for automatic declaration of implicit arguments is on, the default is to automatically set implicit only the strict implicit arguments plus, for historical reasons, a small subset of the non strict implicit arguments. To relax this constraint and to set implicit all non strict implicit arguments by default, use the command

> Unset Strict Implicit.

Conversely, use the command Set Strict Implicit to restore the original mode that declares implicit only the strict implicit arguments plus a small subset of the non strict implicit arguments.

In the other way round, to capture exactly the strict implicit arguments and no more than the strict implicit arguments, use the command:

> Set Strongly Strict Implicit.

Conversely, use the command Unset Strongly Strict Implicit to let the option “Strict Implicit” decide what to do.

Remark: In versions of Coq prior to version 8.0, the default was to declare the strict implicit arguments as implicit.

### 2.7.8 Controlling contextual implicit arguments

By default, Coq does not automatically set implicit the contextual implicit arguments. To tell Coq to infer also contextual implicit argument, use command

> Set Contextual Implicit.

Conversely, use command Unset Contextual Implicit to unset the contextual implicit mode.

### 2.7.9 Controlling reversible-pattern implicit arguments

By default, Coq does not automatically set implicit the reversible-pattern implicit arguments. To tell Coq to infer also reversible-pattern implicit argument, use command

> Set Reversible Pattern Implicit.

Conversely, use command Unset Reversible Pattern Implicit to unset the reversible-pattern implicit mode.

### 2.7.10 Controlling the insertion of implicit arguments not followed by explicit arguments

Implicit arguments can be declared to be automatically inserted when a function is partially applied and the next argument of the function is an implicit one. In case the implicit arguments are automatically declared (with the command Set Implicit Arguments), the command

> Set Maximal Implicit Insertion.

is used to tell to declare the implicit arguments with a maximal insertion status. By default, automatically declared implicit arguments are not declared to be insertable maximally. To restore the default mode for maximal insertion, use command Unset Maximal Implicit Insertion.

### 2.7.11 Explicit applications

In presence of non strict or contextual argument, or in presence of partial applications, the synthesis of implicit arguments may fail, so one may have to give explicitly certain implicit arguments of an application. The syntax for this is (ident:=term) where ident is the name of the implicit argument and term is its corresponding explicit term. Alternatively, one can locally deactivate the hiding of implicit arguments of a function by using the notation @qualid term1..termn. This syntax extension is given Figure 2.4.

> term | ++= | @ qualid term … term
> | | | @ qualid
> | | | qualid argument … argument
> argument | ::= | term
> | | | (ident:=term)

> Figure 2.4: Syntax for explicitly giving implicit arguments

Example (continued):

Coq < Check (p r1 (z:=c)).
p r1 (z:=c)
: R b c -> R a c
Coq < Check (p (x:=a) (y:=b) r1 (z:=c) r2).
p r1 r2
: R a c

### 2.7.12 Renaming implicit arguments

Implicit arguments names can be redefined using the following syntax:

> Arguments qualid name … name : rename

Without the rename flag, Arguments can be used to assert that a given constant has the expected number of arguments and that these arguments are named as expected.

Example (continued):

Coq < Arguments p [s t] _ [u] _: rename.
Coq < Check (p r1 (u:=c)).
p r1 (u:=c)
: R b c -> R a c
Coq < Check (p (s:=a) (t:=b) r1 (u:=c) r2).
p r1 r2
: R a c
Coq < Fail Arguments p [s t] _ [w] _.
The command has indeed failed with message:
=> Error: To rename arguments the "rename" flag must be specified.

### 2.7.13 Deprecated Implicit Arguments command

Before version 8.4 the command to specify the implicit arguments of a constant was Implicit Arguments followed by a bracketed list of identifiers. Starting with Coq 8.4 the Argument command must be used (see 2.7.4).

Coq < Require Import List.
Coq < Implicit Arguments map [A B].
Warning: Implicit Arguments is deprecated; use Arguments instead
Coq < Implicit Arguments length [[A]].
Warning: Implicit Arguments is deprecated; use Arguments instead

The first example declares the arguments of map named A and B implicit. The second one declares the argument named A implicit and maximally inserted.

### 2.7.14 Displaying what the implicit arguments are

To display the implicit arguments associated to an object, and to know if each of them is to be used maximally or not, use the command

> Print Implicit qualid.

### 2.7.15 Explicit displaying of implicit arguments for pretty-printing

By default the basic pretty-printing rules hide the inferable implicit arguments of an application. To force printing all implicit arguments, use command

> Set Printing Implicit.

Conversely, to restore the hiding of implicit arguments, use command

> Unset Printing Implicit.

By default the basic pretty-printing rules display the implicit arguments that are not detected as strict implicit arguments. This “defensive” mode can quickly make the display cumbersome so this can be deactivated by using the command

> Unset Printing Implicit Defensive.

Conversely, to force the display of non strict arguments, use command

> Set Printing Implicit Defensive.

See also: Set Printing All in Section 2.9.

### 2.7.16 Interaction with subtyping

When an implicit argument can be inferred from the type of more than one of the other arguments, then only the type of the first of these arguments is taken into account, and not an upper type of all of them. As a consequence, the inference of the implicit argument of “=” fails in

Coq < Check nat = Prop.

but succeeds in

Coq < Check Prop = nat.

### 2.7.17 Deactivation of implicit arguments for parsing

Use of implicit arguments can be deactivated by issuing the command:

> Set Parsing Explicit.

In this case, all arguments of constants, inductive types, constructors, etc, including the arguments declared as implicit, have to be given as if none arguments were implicit. By symmetry, this also affects printing. To restore parsing and normal printing of implicit arguments, use:

> Set Parsing Explicit.

### 2.7.18 Canonical structures

A canonical structure is an instance of a record/structure type that can be used to solve equations involving implicit arguments. Assume that qualid denotes an object (Build_struc c1 … cn) in the structure struct of which the fields are x1, ..., xn. Assume that qualid is declared as a canonical structure using the command

> Canonical Structure qualid.

Then, each time an equation of the form (xi _)=βδιζci has to be solved during the type-checking process, qualid is used as a solution. Otherwise said, qualid is canonically used to extend the field ci into a complete structure built on ci.

Canonical structures are particularly useful when mixed with coercions and strict implicit arguments. Here is an example.

Coq < Require Import Relations.
Coq < Require Import EqNat.
Coq < Set Implicit Arguments.
Coq < Unset Strict Implicit.
Coq < Structure Setoid : Type :=
Coq < {Carrier :> Set;
Coq < Equal : relation Carrier;
Coq < Prf_equiv : equivalence Carrier Equal}.
Coq < Definition is_law (A B:Setoid) (f:A -> B) :=
Coq < forall x y:A, Equal x y -> Equal (f x) (f y).
Coq < Axiom eq_nat_equiv : equivalence nat eq_nat.
Coq < Definition nat_setoid : Setoid := Build_Setoid eq_nat_equiv.
Coq < Canonical Structure nat_setoid.

Thanks to nat_setoid declared as canonical, the implicit arguments A and B can be synthesized in the next statement.

Coq < Lemma is_law_S : is_law S.
1 subgoal
============================
is_law (A:=nat_setoid) (B:=nat_setoid) S

Remark: If a same field occurs in several canonical structure, then only the structure declared first as canonical is considered.

Variants:

1. Canonical Structure ident := term : type.
   Canonical Structure ident := term.
   Canonical Structure ident : type := term.

   These are equivalent to a regular definition of ident followed by the declaration

   Canonical Structure ident.

See also: more examples in user contribution category (Rocq/ALGEBRA).

#### Print Canonical Projections.

This displays the list of global names that are components of some canonical structure. For each of them, the canonical structure of which it is a projection is indicated. For instance, the above example gives the following output:

Coq < Print Canonical Projections.
eq_nat_equiv <- Prf_equiv ( nat_setoid )
eq_nat <- Equal ( nat_setoid )
nat <- Carrier ( nat_setoid )

### 2.7.19 Implicit types of variables

It is possible to bind variable names to a given type (e.g. in a development using arithmetic, it may be convenient to bind the names n or m to the type nat of natural numbers). The command for that is

> Implicit Types ident … ident : type

The effect of the command is to automatically set the type of bound variables starting with ident (either ident itself or ident followed by one or more single quotes, underscore or digits) to be type (unless the bound variable is already declared with an explicit type in which case, this latter type is considered).

Example:

Coq < Require Import List.
Coq < Implicit Types m n : nat.
Coq < Lemma cons_inj_nat : forall m n l, n :: l = m :: l -> n = m.
1 subgoal
============================
forall m n (l : Datatypes.list nat), n :: l = m :: l -> n = m
Coq < intros m n.
1 subgoal
m : nat
n : nat
============================
forall l : Datatypes.list nat, n :: l = m :: l -> n = m
Coq < Lemma cons_inj_bool : forall (m n:bool) l, n :: l = m :: l -> n = m.
1 subgoal
============================
forall (m n : bool) (l : Datatypes.list bool), n :: l = m :: l -> n = m

Variants:

1. Implicit Type ident : type
   This is useful for declaring the implicit type of a single variable.
2. Implicit Types ( ident1,1…ident1,k1 : term1 ) … ( identn,1…identn,kn : termn ).
   Adds n blocks of implicit types with different specifications.

### 2.7.20 Implicit generalization

Implicit generalization is an automatic elaboration of a statement with free variables into a closed statement where these variables are quantified explicitly. Implicit generalization is done inside binders starting with a ``` and terms delimited by ``{ }` and ``( )`, always introducing maximally inserted implicit arguments for the generalized variables. Inside implicit generalization delimiters, free variables in the current context are automatically quantified using a product or a lambda abstraction to generate a closed term. In the following statement for example, the variables n and m are autamatically generalized and become explicit arguments of the lemma as we are using ``( )`:

Coq < Generalizable All Variables.
Coq < Lemma nat_comm : ‘(n = n + 0).
1 subgoal
============================
forall n, n = n + 0

One can control the set of generalizable identifiers with the Generalizable vernacular command to avoid unexpected generalizations when mistyping identifiers. There are three variants of the command:

> Generalizable (All|No) Variable(s)? (ident1 identn)?.

Variants:

1. Generalizable All Variables. All variables are candidate for generalization if they appear free in the context under a generalization delimiter. This may result in confusing errors in case of typos. In such cases, the context will probably contain some unexpected generalized variable.
2. Generalizable No Variables. Disable implicit generalization entirely. This is the default behavior.
3. Generalizable Variable(s)? ident1 identn. Allow generalization of the given identifiers only. Calling this command multiple times adds to the allowed identifiers.
4. Global Generalizable Allows to export the choice of generalizable variables.

One can also use implicit generalization for binders, in which case the generalized variables are added as binders and set maximally implicit.

Coq < Definition id ‘(x : A) : A := x.
Coq < Print id.
id = fun (A : Type) (x : A) => x
: forall A : Type, A -> A
Argument A is implicit and maximally inserted
Argument scopes are [type_scope _]

The generalizing binders ``{ }` and ``( )` work similarly to their explicit counterparts, only binding the generalized variables implicitly, as maximally-inserted arguments. In these binders, the binding name for the bound object is optional, whereas the type is mandatory, dually to regular binders.

## 2.8 Coercions

Coercions can be used to implicitly inject terms from one class in which they reside into another one. A class is either a sort (denoted by the keyword Sortclass), a product type (denoted by the keyword Funclass), or a type constructor (denoted by its name), e.g. an inductive type or any constant with a type of the form forall (x1:A1) .. (xn:An), s where s is a sort.

Then the user is able to apply an object that is not a function, but can be coerced to a function, and more generally to consider that a term of type A is of type B provided that there is a declared coercion between A and B. The main command is

> Coercion qualid : class1 >-> class2.

which declares the construction denoted by qualid as a coercion between class1 and class2.

More details and examples, and a description of the commands related to coercions are provided in Chapter 18.

## 2.9 Printing constructions in full

Coercions, implicit arguments, the type of pattern-matching, but also notations (see Chapter 12) can obfuscate the behavior of some tactics (typically the tactics applying to occurrences of subterms are sensitive to the implicit arguments). The command

> Set Printing All.

deactivates all high-level printing features such as coercions, implicit arguments, returned type of pattern-matching, notations and various syntactic sugar for pattern-matching or record projections. Otherwise said, Set Printing All includes the effects of the commands Set Printing Implicit, Set Printing Coercions, Set Printing Synth, Unset Printing Projections and Unset Printing Notations. To reactivate the high-level printing features, use the command

> Unset Printing All.

## 2.10 Printing universes

The following command:

> Set Printing Universes

activates the display of the actual level of each occurrence of Type. See Section 4.1.1 for details. This wizard option, in combination with Set Printing All (see section 2.9) can help to diagnose failures to unify terms apparently identical but internally different in the Calculus of Inductive Constructions. To reactivate the display of the actual level of the occurrences of Type, use

> Unset Printing Universes.

The constraints on the internal level of the occurrences of Type (see Section 4.1.1) can be printed using the command

> Print [Sorted] Universes.

If the optional Sorted option is given, each universe will be made equivalent to a numbered label reflecting its level (with a linear ordering) in the universe hierarchy.

This command also accepts an optional output filename:

> Print [Sorted] Universes string.

If string ends in .dot or .gv, the constraints are printed in the DOT language, and can be processed by Graphviz tools. The format is unspecified if string doesn’t end in .dot or .gv.

## 2.11 Existential variables

Coq terms can include existential variables. An existential variable is a placeholder intended to eventually be replaced by an actual subterm though which subterm it will be replaced by is still unknown.

Existential variables are generated in place of unsolvable implicit arguments when using commands such as Check (see Section 6.3.1) or in place of unsolvable instances when using tactics such as eapply (see Section 4). They can only appear as the result of a command displaying a term and they are represented by “?” followed by a number. They cannot be entered by the user (though they can be generated from “_” when the corresponding implicit argument is unsolvable).

A given existential variable name can occur several times in a term meaning the corresponding expected instance is shared. Each existential variable is relative to a context, as shown by Show Existential when in the process of proving a goal (see Section 10). Henceforth, each occurrence of an existential variable in a term is subject to an instance of the variables of its context of definition which is specific to this occurrence.

### 2.11.1 Explicit displaying of existential instances for pretty-printing

The command:

> Set Printing Existential Instances

activates the display of how the context of an existential variable is instantiated on each of its occurrences.

To deactivate the display of the instances of existential variables, use

> Unset Printing Existential Instances.