10.6092/issn.1972-5787/4712
In this thesis we give an algebraic characterization of the syntax and semantics of simply–typed languages. More precisely, we characterize simply–typed binding syntax equipped with reduction rules via a universal property, namely as the initial object of some category.We specify a language by a 2–signature (Σ, A), that is, a signature on two levels: the syntactic level Σ specifies the sorts and terms of the language, and associates a sort to each term. The semantic level A specifies, through inequations, reduction rules on the terms of the language. To any given 2–signature (Σ, A) we associate a category of “models” of (Σ, A). We prove that this category has an initial object, which integrates the terms freely generated by Σ and the reduction relation — on those terms — generatedby A. We call this object the programming language generated by (Σ, A).Initiality provides an iteration principle which allows to specify translations on the syntax, possibly to a language over different sorts. Furthermore, translations specified via the iteration principle are by construction type–safe and faithful with respect to reduction.To illustrate our results, we consider two examples extensively: firstly, we specify a double negation translation from classical to intuitionistic propositional logic via the category–theoretic iteration principle. Secondly, we specify a translation from PCF to the untyped lambda calculus which is faithful with respect to reduction in the source andtarget languages.In a second part, we formalize some of our initiality theorems in the proof assistant Coq. The implementation yields a machinery which, when given a 2–signature, returns an implementation of its associated abstract syntax together with certified substitution operation, iteration operator and a reduction relation generated by the specified reduction rules.
application/pdf
1972-5787
4712
2
en
Benedikt Ahrens
Journal of Formalized Reasoning
initial semantics
Initiality for Typed Syntax and Semantics
Text.Serial.Journal
https://jfr.unibo.it/
8
Ph.D. Thesis
2015-04-17
2015-02-13
2015-04-17
2016-12-23
1-155
JFR
Benedikt Ahrens
2015/04/17
10.6092/issn.1972-5787/4712
1
1972-5787
2
initial semantics
en
155
Initiality for Typed Syntax and Semantics
https://jfr.unibo.it/article/download/4712/4796
8
Initiality for Typed Syntax and Semantics


BENEDIKT AHRENS
Université Nice Sophia Antipolis, France


In this thesis we give an algebraic characterization of the syntax and semantics of simplytyped
languages. More precisely, we characterize               simplytyped binding syntax equipped with reduction
rules   via a   universal property,     namely as the initial object of some category.
   We specify a language by a          2signature (Σ, A),      that is, a signature on two levels: the    syntactic
level   Σ   species the sorts and terms of the language, and associates a sort to each term.                   The
semantic     level   A   species, through   inequations,      reduction rules on the terms of the language. To
any given 2signature         (Σ, A)   we associate a category of models of        (Σ, A).   We prove that this
category has an initial object, which integrates the terms freely generated by                 Σ   and the reduction
relation  on those terms  generated by                  A.    We call this object the   programming language
generated by (Σ, A).
   Initiality provides an       iteration principle      which allows to specify translations on the syntax,
possibly to a language over dierent sorts. Furthermore, translations specied via the iteration
principle are by construction          typesafe   and   faithful with respect to reduction.
   To illustrate our results, we consider two examples extensively:                 rstly, we specify a double
negation translation from classical to intuitionistic propositional logic via the categorytheoretic
iteration principle. Secondly, we specify a translation from              PCF   to the untyped lambda calculus
which is faithful with respect to reduction in the source and target languages.
   In a second part, we formalize some of our initiality theorems in the proof assistant Coq. The
implementation yields a machinery which, when given a 2signature, returns an implementation
of its associated abstract syntax together with certied substitution operation, iteration operator
and a reduction relation generated by the specied reduction rules.




                                                   Journal of Formalized Reasoning Vol. 8, No. 2, 2015, Pages 1155.
2     ·     B. Ahrens




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
UNIVERSITÉ NICE SOPHIA ANTIPOLIS - UFR Sciences

            École Doctorale Sciences Fondamentales et Appliquées




                               THÈSE
                          Docteur en Sciences
                              pour obtenir le titre de



                       Spécialité   Mathématiques
                            présentée et soutenue par

                            Benedikt AHRENS

 Initiality for Typed Syntax and Semantics

                   Thèse dirigée par   André HIRSCHOWITZ
                             soutenue le 23 mai 2012




                                Membres du jury :


     M.   PierreLouis    CURIEN                 Rapporteur et Examinateur
     M.   André           HIRSCHOWITZ            Directeur de thèse
     M.   Marco           MAGGESI                Examinateur
     M.   Laurent         REGNIER                Rapporteur et Examinateur
     M.   Carlos          SIMPSON                Examinateur




Laboratoire Jean-Alexandre Dieudonné, Université de Nice, Parc Valrose, 06108
NICE
4     ·     B. Ahrens




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                          Initiality for Typed Syntax and Semantics        ·     5




Contents

1 Introduction                                                                                   9
   1.1     Motivation: Translations from       PCF   to   ULC   . . . . . . . . . . . . . .      9
   1.2     Initial Semantics     . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      10
           1.2.1   Example: Peano Axioms . . . . . . . . . . . . . . . . . . . . .              11
           1.2.2   Initial Algebras . . . . . . . . . . . . . . . . . . . . . . . . . .         12
           1.2.3   Adding Variable Binding . . . . . . . . . . . . . . . . . . . . .            13
           1.2.4   Adding Substitution       . . . . . . . . . . . . . . . . . . . . . . .      14
           1.2.5   Adding Types . . . . . . . . . . . . . . . . . . . . . . . . . . .           14
           1.2.6   Adding Reductions . . . . . . . . . . . . . . . . . . . . . . . .            16
   1.3     Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .          17
           1.3.1   Extended Initiality for Varying Sorts . . . . . . . . . . . . . .            18
           1.3.2   Integrating Reduction Rules . . . . . . . . . . . . . . . . . . .            18
           1.3.3   Main Theorem: Initiality for SimplyTyped Syntax with Re-
                   duction     . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      19
           1.3.4   A Computer Implementation for Specifying Syntax and Se-
                   mantics     . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      19
   1.4     Synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .         19
   1.5     Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .           21
           1.5.1   Translations from     PCF   . . . . . . . . . . . . . . . . . . . . . .      21
           1.5.2   Initial Semantics     . . . . . . . . . . . . . . . . . . . . . . . . .      21
           1.5.3   Formalization of Syntax . . . . . . . . . . . . . . . . . . . . .            23
           1.5.4   Published Work . . . . . . . . . . . . . . . . . . . . . . . . . .           24




Theory                                                                                         24
2 CategoryTheoretic Constructions                                                             24
   2.1     Categories, Functors & Transformations           . . . . . . . . . . . . . . . .     24
           2.1.1   Two Denitions of Categories . . . . . . . . . . . . . . . . . .             25
           2.1.2   Functors & Natural Transformations . . . . . . . . . . . . . .               27
           2.1.3   More Examples, Notations . . . . . . . . . . . . . . . . . . . .             28
   2.2     Monads & Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . .             31
           2.2.1   Denitions      . . . . . . . . . . . . . . . . . . . . . . . . . . . .      31
           2.2.2   Constructions on Monads and Modules              . . . . . . . . . . . .     35
           2.2.3   Monads on Set Families        . . . . . . . . . . . . . . . . . . . . .      36
   2.3     Alternative Denitions for Monads & Modules              . . . . . . . . . . . .     38
   2.4     Relative Monads and Modules . . . . . . . . . . . . . . . . . . . . . .              42
           2.4.1   Denitions      . . . . . . . . . . . . . . . . . . . . . . . . . . . .      43
           2.4.2   Constructions on Relative Monads and Modules                . . . . . . .    49
           2.4.3   Derivation & Fibre . . . . . . . . . . . . . . . . . . . . . . . .           50


3 Simple Type Systems                                                                          52
   3.1     Signatures for Types . . . . . . . . . . . . . . . . . . . . . . . . . . .           53
   3.2     Zsidó's Theorem Reviewed . . . . . . . . . . . . . . . . . . . . . . . .             55
           3.2.1   Signatures for Terms . . . . . . . . . . . . . . . . . . . . . . .           55


                                               Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
6     ·     B. Ahrens




          3.2.2    Representations . . . . . . . . . . . . . . . . . . . . . . . . . .            59
          3.2.3    Initiality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .         60
    3.3   Extending Zsidó's Theorem to Varying Types . . . . . . . . . . . . .                    60
          3.3.1    Signatures for Types & Terms . . . . . . . . . . . . . . . . . .               61
          3.3.2    Representations of Typed Signatures . . . . . . . . . . . . . .                66
          3.3.3    Initiality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .         68
    3.4   Logics and Logic Translations . . . . . . . . . . . . . . . . . . . . . .               71
          3.4.1    Signatures of Classical and Intuitionistic Logic            . . . . . . . .    71
          3.4.2    Translation via Initiality . . . . . . . . . . . . . . . . . . . . .           72
          3.4.3    Remarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .            73


4 Reductions for Untyped Syntax                                                                   73
    4.1   1Signatures       . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .        75
    4.2   Representations of 1Signatures . . . . . . . . . . . . . . . . . . . . .               77
    4.3   Inequations     . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .         79
    4.4   Initiality for 2Signatures       . . . . . . . . . . . . . . . . . . . . . . . .       82


5 Simple Type Systems with Reductions                                                             86
    5.1   1Signatures       . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .        86
    5.2   Representations of 1Signatures . . . . . . . . . . . . . . . . . . . . .               88
    5.3   Inequations     . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .         89
    5.4   Initiality for 2Signatures       . . . . . . . . . . . . . . . . . . . . . . . .       92




Computer Implementation                                                                          95
6 Formalizing Category Theory in Coq                                                             95
    6.1   About the Proof Assistant         Coq    . . . . . . . . . . . . . . . . . . . . .      96
    6.2   Formalizing Algebraic Structures             . . . . . . . . . . . . . . . . . . . .    97
    6.3   Formalizing Categories . . . . . . . . . . . . . . . . . . . . . . . . . .              99
          6.3.1    Which Denition to Formalize  Dependent HomSets? . . .                       99
          6.3.2    Setoidal Equality on Morphisms              . . . . . . . . . . . . . . . . 100
          6.3.3    Coq   Setoids and Setoid Morphisms . . . . . . . . . . . . . . . 100
          6.3.4    Coq   Implementation of Categories            . . . . . . . . . . . . . . . 101
          6.3.5    The Categories of Interest . . . . . . . . . . . . . . . . . . . . 102
          6.3.6    Initial Objects      . . . . . . . . . . . . . . . . . . . . . . . . . . 103
          6.3.7    Interlude on the     Program    feature     . . . . . . . . . . . . . . . . 103
          6.3.8    Retyping and Option . . . . . . . . . . . . . . . . . . . . . . . 103
    6.4   Monads, Modules and their Morphisms . . . . . . . . . . . . . . . . . 105
    6.5   Relative Monads, Formalized           . . . . . . . . . . . . . . . . . . . . . . 106


7 Formalization of Zsidó's theorem                                                               107
    7.1   Signatures & Representations . . . . . . . . . . . . . . . . . . . . . . 108
          7.1.1    Using Lists for Algebraic Arities & Signatures . . . . . . . . . 108
          7.1.2    Modules and Morphisms for Arities . . . . . . . . . . . . . . . 109
    7.2   Construction of the Initial Object . . . . . . . . . . . . . . . . . . . . 113
          7.2.1    The Terms Generated by a Signature . . . . . . . . . . . . . . 114


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                      Initiality for Typed Syntax and Semantics        ·     7




        7.2.2    Monad Structure on the Set of Terms          . . . . . . . . . . . . . 114
        7.2.3    A Representation in the Monad of Terms           . . . . . . . . . . . 116
        7.2.4    Weak Initiality for the Representation in the Term Monad . . 116
        7.2.5    Uniqueness and Initiality    . . . . . . . . . . . . . . . . . . . . 117
  7.3   Remarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118


8 Initiality for Untyped 2Signatures, Formalized                                          118
  8.1   Arities by Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
  8.2   Representations of a 1Signature      . . . . . . . . . . . . . . . . . . . . 119
  8.3   Morphisms of Representations . . . . . . . . . . . . . . . . . . . . . . 121
  8.4   Category of Representations . . . . . . . . . . . . . . . . . . . . . . . 122
  8.5   Initiality without Inequations . . . . . . . . . . . . . . . . . . . . . . 123
  8.6   Inequations and Initial Representation of a 2Signature            . . . . . . . 125
  8.7   Λβ :   Lambda Calculus with beta reduction . . . . . . . . . . . . . . . 128


9 A Faithful Translation of PCF to ULC                                                     129
  9.1   Representations of   PCF     . . . . . . . . . . . . . . . . . . . . . . . . . 130
  9.2   Morphisms of Representations . . . . . . . . . . . . . . . . . . . . . . 132
  9.3   Digression on Equal Fibre Modules in       Coq   . . . . . . . . . . . . . . . 134
  9.4   Equality of Morphisms, Category of Representations            . . . . . . . . . 135
  9.5   One Particular Representation        . . . . . . . . . . . . . . . . . . . . . 137
  9.6   Initiality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
  9.7   A Representation of    PCF   in the Untyped Lambda Calculus            . . . . . 143


10 Conclusions and Further Work                                                            146
  10.1 Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
  10.2 Further Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146


A Syntax and Semantics of Lambda Calculus and PCF                                          148
  A.1   Syntax of Lambda Calculus and       PCF . .    . . . . . . . . . . . . . . . . 148
  A.2   Semantics of Lambda Calculus       and PCF     . . . . . . . . . . . . . . . . 149


References                                                                                 151




                                           Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
8     ·     B. Ahrens




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                          Initiality for Typed Syntax and Semantics             ·   9




1.    INTRODUCTION
In this thesis we give a characterization, via a universal property, of the syntax
and semantics of simplytyped languages with variable binding. More precisely, we
characterize the terms and sorts associated to a signature, equipped with reduction
rules, as the initial object in some category. Via the iteration principle stemming
from initiality, translations between languages, possibly over dierent sets of sorts,
can be specied in a convenient and economic way. Furthermore, translations thus
specied are ensured to be faithful with respect to reduction in the source and
target languages, as well as compatible in a suitable sense with substitution on
either side.

1.1    Motivation: Translations from PCF to ULC
As an introductory example, consider translations from the programming language
PCF,    introduced by Plotkin [Plo77], to the untyped lambda calculus                  ULC,   invented
by Church [Chu36].       A detailed account of both languages is given in Appx. A.
These two languages are paradigmatic in the sense that                       PCF   may be considered
a rather highlevel language, equipped with a type system, whereas the untyped
lambda calculus represents a lowlevel, untyped language.                      We specify a map     f
from the set of    PCF   terms to the set of lambda terms as in Fig. 1 (cf. [Pho93]),
with a suitable function    g   from the set of constants of            PCF   to lambda terms, e.g.,



                                          f (⊥A ) = Ω
                                           f (cA ) = g(c)
                                          f (xA ) = x
                                          f (s@t) = f (s)@f (t)
                                        f (λx.M ) = λx.f (M )
                                   f (FixA (M )) = Θ@f (M )


                             Fig. 1.   Translation from     PCF   to   ULC

g(T) := λxy.x,    and suitable constants of the lambda calculus, e.g.,
                                   
 Θ := λx.λy.(y(xxy)) λx.λy.(y(xxy))                  (Turing xed point combinator) and

 Ω := (λx.xx)(λx.xx) .
Of course, dierent such translations exist; for instance, one may choose to translate
Fix to a dierent xed point combinator or one chooses a dierent representation
g 0 for the constants of PCF in the lambda calculus, yielding a dierent translation
f 0 : PCF → ULC.
     In this thesis we present a categorytheoretic framework to specify such transla-
tions of a language to another. The challenges are

                                                                         1
the varying sets of sorts in source and target languages                    and

to capture compatibility of such translations with structure  such as substitu-
     tion and reduction  in the source and target languages.


1 Here we consider untyped languages to be singlesorted.

                                                Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
10      ·     B. Ahrens




We construct a category in which languages such as                        PCF   and   ULC   are objects,
and in which the above translation            f : PCF → ULC          is a morphism. As it turns out,
the preceding sentence is imprecise and needs to be rened: more precisely, in the
category we construct the translation             f    is an    initial morphism f : PCF → ULC,
that is, its source      PCF   is the initial object. Now, as we have seen, there are several
                         PCF to the lambda calculus, and the above translation
possible translations from
f : PCF → ULC cannot be an initial morphism in a category where objects are just
                                           0                     0
languages  otherwise we would have f = f for any translation f : PCF → ULC.
Thus the objects in the category we construct are not just languages, but languages
with additional structure, allowing us to distinguish dierent initial morphisms
f, f 0 : PCF → ULC,


                                                   f          3 (ULC, ψ)
                                     (PCF, φ)
                                                  f0
                                                          +
                                                              (ULC, ψ 0 ).
                              (PCF, φ) yields the following iteration principle: spec-
In this category, initiality of
ifying an iterative translationf : PCF → ULC is equivalent to specifying the extra
structure ψ of the lambda calculus ULC. We do not yet explain what this addi-
                                          0
tional structure, here denoted φ, ψ and ψ , looks like, but refer instead to Sect. 1.2.1
for an instructive example.
     A natural question then is whether  or better, in what sense  the translation
f   specied in Fig. 1 is compatible with the respective reductions in the source and
target languages. Phoa [Pho93] gives an answer to this question; in particular, the
translation   f   is   faithful   in the sense that

                                  t PCF t0   implies    f (t) β f (t0 ) .
In this thesis we provide a categorytheoretic framework which allows to specify,
via a universal property, such faithful translations between languages with variable
binding over dierent sets of sorts.


1.2     Initial Semantics
Initial Semantics        characterizes the terms of a language associated to a             signature S
as the initial object in some category  whose objects we call                     Semantics of S ,
yielding a concise, highlevel, denition of the abstract syntax                   associated to S . In
more detail, the following ingredients are used:

     Signature.   A    signature    species abstractly and concisely the syntax and seman-
tics of a language.

     Category of Representations.         To any signature        S we associate a category of mod-
els of that signature, the objects of which we call                representations of S .
     Initiality. In this category       of representations       of S we exhibit the initial object,
the    language generated by S .
The motivation for Initial Semantics are twofold: rstly, Initial Semantics provides
a categorytheoretic denition  via a universal property  of the syntax and

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                        Initiality for Typed Syntax and Semantics         ·      11




semantics freely generated by a signature. Secondly, initiality yields an                iteration
operator which allows for an economic and             convenient specication of morphisms
 translations  from the initial object to           other languages.
  Depending on the richness of the language we want to dene, we need a suit-
able notion of signature and, accordingly, of representation of that signature. The
language features we consider in this thesis are the following:

  Variable binding.    We consider binding constructors on the             term level,    such as
lambda abstraction.

  Typing.    We consider   simple   type systems, such as the simplytyped lambda cal-
culus and, via the CurryHoward isomorphism, propositional logic (cf. Sect. 3.4).

  Reduction.     We consider semantics in form of reduction rules on terms, such as
beta reduction,

                                 λx.M (N ) ; M [x := N ] .
For the integration of each of the features above, the notions of signature and repre-
sentation have to be adapted to accommodate the increasing amount of information
which must be given to uniquely specify a language.
  One of our goals is to use Initial Semantics in order to treat the last question of
the preceding section: we would like to translate from one language into another
 possibly over dierent sets of sorts , using a universal, categorytheoretic
construction.    This construction should take into account as much structure as
possible.   By this we mean that the translations under consideration should by
construction be compatible, for instance, with typing and reduction in the source
and target language. A more indepth description of those structures is given in
Sects. 1.2.3, 1.2.4, 1.2.5 and 1.2.6.
  In Sect. 1.2.1 we explain the notion of        signature   and    representation   for a simple
inductive data type, the natural numbers. The following sections sketch the changes
that have to be made in order to integrate variable binding, substitution, typing
and reduction rules, respectively. In Sect. 1.3 we summarize the contributions of
this thesis, whereas in Sect. 1.4 we give a sectionwise overview of its contents.

  1.2.1     Example: Peano Axioms.       We introduce the notion of       signature   and     repre-
sentation   using the example of the natural numbers; in line with the triple structure
mentioned at the beginning of Sect. 1.2, our goal is to give a signature for the natu-
ral numbers and to associate to it a category of representations whose initial object
is given by the natural numbers.
  As a suitable    signature,   consider the following map from a two elements set to
natural numbers:

                                 N := {z 7→ 0 ,         s 7→ 1} .
Intuitively, it says that the natural numbers are built from two          constructors, namely
a 0ary operator (i.e. a constant), say,         z,    the zero constant  and a unary
operator, say, s  the     successor function.
  A   representation of    the signature     N is given by a triple (X, Z, S) of a set X
together with a constant    Z ∈ X and a unary operation S : X → X . A morphism
to another such triple    (X0 , Z0 , S0 ) is a map f : X → X0 such that
                           f (Z) = Z0      and        f ◦ S = S0 ◦ f .                         (1.1)

                                              Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
12      ·      B. Ahrens




This category has an    initial object (N, Zero, Succ) given by the natural numbers N
equipped with the constant      Zero = 0 and the successor function Succ : N → N.
   Initiality of N gives a way to specify iterative functions [Ven00] from N to any
set X by equipping X with a constant Z ∈ X and a unary map S : X → X , i.e.
making the set X the carrier of an object (X, Z, S) ∈ N . A dierent choice of
Z 0 ∈ X and S 0 : X → X yields a dierent iterative map N → X .
     Put dierently, reading Disp. (1.1) dynamically rather than statically, i.e. as a
reduction from left to right rather than as equations, shows that functions on the
initial object   N   can be dened by         pattern matching,        where the righthand side of
the matching must obey a particular form.

   Remark 1.1 (Digression on Natural Numbers Object). The very same denition
is also used to dene a natural numbers object in any category C with a terminal
object 1; just replace Z ∈ X and S : X → X by morphisms z : 1 → X and
s : X → X in C . More precisely, we call natural numbers object the triple (N :
C, Zero : 1 → N, Succ : N → N) if, for any triple (X, z, s) of an object X ∈ C and
morphisms z and s as above, there exists a unique morphism f : N → X such that
the following diagrams commute:


                           1
                                 Zero   /N                       N
                                                                     Succ    /N

                                          f                  f                  f
                                 z
                                                                            
                                         X                   X               /X
                                                                      s

For details we refer to Mac Lane and Moerdijk's book [MLM92].

     1.2.2   Initial Algebras.    The term Initial Algebra is best explained using an-
                                               signature functor Σ : Set → Set.
other viewpoint, where a signature is given by a
The category in question then is the category ΣAlg of algebras of the functor
Σ, that is, the category whose objects are pairs (X, f ) of a set X and a map
f : ΣX → X . A morphism to another such algebra (Y, g) is given by a map
h : X → Y such that

                                          ΣX
                                                     Σh   / ΣY

                                           f                     g
                                                            
                                              X            /Y
                                                      h

commutes. The example of Sect. 1.2.1 is equivalently given by the signature functor
N : X 7→ 1 + X ,     with initial algebra

                                                   [Zero,Succ]
                                        1 + N −−−−−−−→ N .
Another example is that of          lists (of   nite length) of a given type          A:    let   F (X) :=
1 + A × X.      The initial    F algebra is    given by the set       [A]   of lists over   A,
                                                      [nil,cons]
                                     1 + A × [A] −−−−−→ [A] .


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                               Initiality for Typed Syntax and Semantics             ·    13




  1.2.3         Adding Variable Binding.         When passing to syntax         with variable binding,
the question of how to model binding arises.                    The following representations of
binding are among the most frequently used:

Nominal syntax using named abstraction (A being a set of                        atoms ),   e.g.,

                                                λ : [A]T → T
HigherOrder Abstract Syntax (HOAS), e.g.,

                                               λ : (T → T ) → T
  and its       weak   variant, e.g.,

                                               λ : (A → T ) → T
Nested Data Types as presented in [BM98], e.g.,

                                          λ : T (X + 1) → T (X)
Note that the encoding via nested data types diers conceptually from the others
in that here the set        T   of terms is parametrized explicitly by a          context, i.e. a set X
of variables possibly appearing freely in the terms of                 T (X).    Thus   T (X) denotes
the set of terms of the language       T        with free variables in the      set X . The set X + 1
corresponds to an        extended context      with one additional free variable, which is bound
in the abstracted term. It is usually implemented through an inductive data type
(option in Ocaml or the            Maybe monad in Haskell)  whence the term  Nested .
It is also known under the name Heterogenous data type [AR99].

  Example 1.2.           We represent the untyped lambda calculus as a                nested data type
as done, e.g., by Bird and Paterson [BP99]: consider the following inductive type
                                                                           2
ULC : Set → Set         of terms of the untyped lambda calculus :

Inductive ULC (V : Type) : Type :=
  | Var : V −> ULC V
  | Abs : ULC (option V) −> ULC V
  | App : ULC V −> ULC V −> ULC V.

For syntax with binding, arities need to carry information about the binding be-
haviour of their associated constructor. One way to dene such arities is using lists
of natural numbers. The length of a list then indicates the number of arguments
of the constructor, and the             i-th   entry denotes the number of variables that the
constructor binds in the i-th argument. Continuing Ex. 1.2, the signature                           Λ of ULC
is given by

                                  Λ := {app : [0, 0] ,      abs : [1]} .
The map   V 7→ ULC(V ) is in fact functorial: given a map f : V → W , the map
ULC(f ) : ULC(V ) → ULC(W ) renames any free variable v ∈ V in a term by f (v),
yielding a term with free variables in W . Accordingly, the signature Λ should be
represented in functors F : Set → Set instead of in sets, and natural transformations
take the place of maps.

2 We use Set synonymously to Type. Note however, that types behave dierently from sets in

some aspects. In particular, given two (propositionally) equal types           A=B   and   a : A,   we do not
have   a : B.
                                                     Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
14      ·     B. Ahrens




     1.2.4   Adding Substitution.    As mentioned at the beginning of Sect. 1.2, we would
like to integrate as much structure as possible into our category of models. One
such structure is      (captureavoiding) substitution of free variables. To account for
substitution, we consider not plain functors        F : Set → Set as in the preceding
paragraph, but       instead monads on the category Set of sets. Monads are functors
equipped with some extra structure, which we explain by the example of the un-
typed lambda calculus. The map     V 7→ ULC(V ) comes with a (captureavoiding)
simultaneous substitution operation: letV and W be two sets (of variables) and f
be a map f : V → ULC(W ). Given a lambda term t ∈ ULC(V ), we can replace each
                                                                 0
free variable v ∈ V in t by its image under f , yielding a term t ∈ ULC(W ). Fur-
thermore we consider the constructor VarV as a variableasterm map, indexed
by a set of variables V ,

                                     VarV : V → ULC(V ) .
Altenkirch and Reus [AR99] observed that the wellknown algebraic structure
of monad captures those two operations and their properties:                substitution and
variableasterm map turn     ULC into a monad (Def. 2.65) on the category of sets.
  The monad structure of ULC should be compatible in a suitable sense with the
constructors Abs and App of ULC: substitution distributes over constructors. To
capture this distributivity, Hirschowitz and Maggesi [HM07a] consider modules over
a monad (cf. Def. 2.43)  which generalize monadic substitution , and morphisms
of modules  which are natural transformations that are compatible with the
module substitution in a suitable sense. Indeed, the maps

                                    ULC : V 7→ ULC(V ) ,
                                   ULC0 : V 7→ ULC(V + 1)       and

                            ULC × ULC : V 7→ ULC(V ) × ULC(V )
are the underlying maps of such modules (cf. Exs. 2.45, 2.46), and the constructors
Abs    and   App   are morphisms of modules (cf. Exs. 2.47, 2.74).

     1.2.5   Adding Types. Type systems            exist with varying features, ranging from
simplytyped syntax to syntax with dependent types, kinds, polymorphism, etc.
By simplytyped syntax we mean a nonpolymorphic syntax where the set of types
is independent from the set of terms, i.e. type constructors only take types as
arguments. In more sophisticated type systems, types may depend on terms, leading
to more complex denitions of arities and signatures.              The present work is only
concerned with simplytyped languages, such as the simplytyped                λcalculus and
PCF.    We refer to the underlying set of types of a language as         object types or sorts.
     The goal of typing is to   classify   terms according to some criteria. As an example,
one may ask whether a term is of function type, that is, whether it would make
sense to apply it to another term. Once such a classication of terms is achieved,
one can use typing information to          lter   terms according to their types, in order to
pick out only those terms that have the desired type. The classication of terms
through typing thus has a semantic avour. However, we still subsume typing under
the   syntactic    aspect, since it has an impact on the set of terms of the language.
     One way to add types would be to make them part of the terms, as in  λx          : N.x +
4.   However, for    simple type systems     it is possible to separate the worlds of types

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                         Initiality for Typed Syntax and Semantics        ·      15




and terms and consider typing as a map from terms to types, thus giving a simple
mathematical structure to typing. How can we be sure that our terms are well
typed? Despite the separation of types and terms we still want typing to be tightly
integrated into the process of building terms, in order to avoid constructing illtyped
terms. Separation of terms and types seems to contradict this goal. The answer
lies in considering not   one set of terms with a typing map to the set, say, T , of
types, but   a family of sets, indexed by the set T of object types. Term constructors
then can be picky about what terms they take as arguments, accepting only those
terms that have the suitable type. We also consider free variables to be equipped
with an object type.        Put dierently, we do not consider terms over               one   set of
variables, but over a family of sets of variables, indexed by the set of object types.
In other words, we consider a context to be given by a family                (Vt )t∈T   of sets of
variables, where   Vt := V (t) is the set of variables of object type t.      We illustrate our
point of view by means of the example of the simplytyped lambda calculus                     TLC:
  Example 1.3.       Let

                               TTLC ::= ∗ | TTLC ; TTLC
be the set of types of the simplytyped lambda calculus. The set family of simply
typed lambda terms with free variables in           V   is given by the following inductive
family:

Inductive TLC (V : T −> Type) : T −> Type :=
  | Var : forall t, V t −> TLC V t
  | Abs : forall s t TLC (V + s) t −> TLC V (s ∼> t)
  | App : forall s t, TLC V (s ∼> t) −> TLC V s −> TLC V t.
where   V + s := V + {∗s}     denotes context extension by a variable of type            s ∈ TTLC
 the variable which is bound by the constructor           Abs (s, t).   The variables     s and t
range over the set   TTLC   of types. The signature describing the simplytyped lambda
calculus is given in Exs. 3.23 and 3.47.          The preceding paragraph about monads
and modules applies to the simplytyped lambda calculus when replacing sets by
families of sets indexed by     TTLC :   the simplytyped lambda calculus can be given
the structure of a monad (cf. Ex. 2.37)

                                 TLC : SetTTLC → SetTTLC .
The constructors of    TLC    are morphisms of modules (cf. Exs. 2.61, 2.56, 2.60).

  This method of dening exactly the welltyped terms by organizing them into a
family of sets parametrized by object types is called         intrinsic typing [BHKM11] 
as opposed to the    extrinsic typing,   where rst a set of    raw terms is dened, which
is then ltered via a typing predicate. Intrinsic typing delegates object level typing
to the meta language type system, such as the        Coq type system in Ex. 1.3. In this
way, the meta level type checker (e.g.      Coq) sorts out illtyped terms automatically:
writing such a term yields a type error on the meta level.
  Furthermore, the intrinsic encoding comes with a much more convenient recursion
principle; a map to any other type system can simply be dened by specifying its
image on the welltyped terms. When using extrinsic typing, a map on terms would
either have to be dened on the set of      raw   terms, including illtyped ones, or on just

                                               Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
16      ·      B. Ahrens




the welltyped terms by specifying an additional propositional argument expressing
the welltypedness of the term argument. Benton et al. give detailed explanation
about intrinsic typing in a recently published paper [BHKM11].

     1.2.6   Adding Reductions.     semantics of a programming language describes
                                              The
how programmes of that language     evaluate. For functional programming languages
as considered in this thesis, evaluation  or computation  is done by reduction.
As an example, the evaluation of the term 7 + 5 of a hypothetical arithmetic pro-
gramming language to its value 12 is done by a series of reductions, whose precise
form depends on the semantics of the language in question. Typical rules, which
specify how terms reduce, are given in Sect. A.2 for the example languages of the
lambda calculus and          PCF.
     Given a set     A   of such reduction rules, one may consider the relation generated
by these rules.          More precisely, following Barendregt and Barendsen [BB94], we
consider several         closures   of those rules:

     Propagation into subterms.                   A relation   R   is called   compatible if it is closed under
propagation into subterms, that is, if for any constructor                        f of arity n and any i ≤ n,
 M ;R N ⇒ f (x1 , . . . , xi1 , M, xi+1 , . . . , xn ) ;R f (x1 , . . . , xi1 , N, xi+1 , . . . , xn ) .
     Reduction.     A relation      R   is a       reduction relation     if it is compatible, reexive and
transitive.

     Equivalence.     A relation        R    is a    congruence      if it is a compatible equivalence rela-
tion.

To the set     A    of rules we associate three relations generated by     A, which are the
smallest relations that contain        A and are a compatible relation, a reduction relation
and a congruence,          respectively. We denote these relations, in this order, by →A ,
A     and   =A ,   respectively.

     Remark 1.4      (Digression on Reduction Strategies).                       Suppose we have a term in
which reduction rules are applicable in several places, such as in the term

                                        ((λx.M )N )((λy.M 0 )N 0 ) ,
which is     β reducible in the operator and in the operand.                      Here the natural question
arises where one should reduce at rst, in the operator or in the operand (or both in
parallel)  the question about the                    reduction strategy.       More precisely, one considers
the following two properties of rewrite systems:

     Termination.        Are there innite  nonterminating  chains of reductions?

     Conuence.      Suppose a term               t reduces both to t0 as well as to t00 via two dierent
                                            000                   0       00             000
reductions. Is there a term             t         such that both t and t reduce to t ?

Termination and conuence together yield (strong) normalization, an important
property of rewriting systems:                      in a strongly normalizing rewriting system, any
reduction strategy yields the same value for a given term  in particular, any
reduction strategy arrives at a value, i.e. at a term without any more reducible
subterms. To illustrate the concept of termination, we give an example of a lambda
term such that one reduction strategy terminates whereas another one does not;


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                       Initiality for Typed Syntax and Semantics          ·     17




consider the term     (λx.y)(ΩΩ)   with    Ω = (λx.xx)     and a free variable     y.   Reducing
the outermost beta redex results in an irreducible term               y   in one step, whereas
the strategy of reducing at rst the operand           (ΩΩ)    leads to an innite chain of
reductions.

  In this thesis we are interested in the        reduction relation       generated by a set of
rules.   It diers from the congruence by the absence of a             symmetry     rule, which,
while adequate for mathematical reasoning, yields a relation that is too coarse
from a point of view of    computation. In the words of Girard [GTL89], while the
congruence generated by      A emphasizes the static point of view of mathematics,
the reduction relation    associated to A emphasizes the dynamic point of view of
computation.
  To account for reductions, we consider functors and monads whose codomain
is not the category of (families of ) sets, but of (families of )         preordered sets.    The
denition of monad requires the underlying functor to be an endofunctor, but we
do not want to consider preordered contexts  what would be the meaning of this
preorder? The restriction to endofunctors was lifted by Altenkirch et al. [ACU10]
through the introduction of     relative   monads. A relative monad is given by a functor
 not necessarily endo  together with two operations very similar to monadic
variablesasterms and substitution. We thus consider, e.g., the lambda calculus,
as a relative monad associating to any       set X   of variables a   preordered set of lambda
terms (ULC(X), β ),     where the preorder on         ULC(X)     is given by the reduction
relation β generated    by the beta rule of Disp. (A.1), cf. Ex. 2.85.


1.3   Contributions
In this thesis we give, via a universal property, an algebraic characterization of
simplytyped syntax equipped with semantics in form of reduction rules.                       More
precisely, given a pair of a    signature     specifying the types and terms of a lan-
guage  and      inequations   over this signature  specifying reduction rules , we
characterize the terms of the language associated to this signature, equipped with
reduction rules according to the given inequations, as the initial object of a category
of models.
  Our starting point is work on initiality for untyped syntax done by Hirschowitz
and Maggesi [HM07a], and on its generalization to simplytyped syntax by Zsidó
[Zsi10].   In a rst step we extend Zsidó's theorem [Zsi10, Chap. 6] to account
for varying sorts, cf. Sect. 1.3.1.        Afterwards, we integrate reduction rules into
Hirschowitz and Maggesi's [HM07a] purely syntactic initiality result, cf. Sect. 1.3.2.
Finally we obtain our main theorem, which accounts for varying object types as
well as reduction rules, by combining the aforementioned two results, cf. Sect. 1.3.3.
  Furthermore, for the untyped case (cf. Sect. 1.3.2), we provide a formalized proof
in the proof assistant    Coq   of our result, yielding a machinery which, when fed
with a signature for terms and a set of inequations, produces the abstract syntax
associated to the signature, together with the reduction relation generated by the
given inequations.     For the simplytyped case, we formalize the instantiation of
our main result (cf. Sect. 1.3.3) to the signature of the programming language
PCF   [Plo77].
  We now explain our contributions and approaches in more detail:


                                               Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
18       ·      B. Ahrens




     1.3.1    Extended Initiality for Varying Sorts.        In her PhD thesis [Zsi10, Chap. 6],
Zsidó proves an initiality theorem for the abstract syntax associated to a simply
typed signature. However, the models (or representations) she considers, among
which the abstract syntax is the initial one, are all models over the same set of
sorts. In this way, the iteration principle obtained by initiality does not allow the
specication of a translation to a term language over a dierent set of sorts. We
adapt Zsidó's theorem by introducing     typed signatures. A typed signature (S, Σ)
species a set of    sorts                          S , as well as a set of simplytyped
                             via an algebraic signature
terms over these sorts via a term signature Σ over S . A representation R of such
a typed signature is then given by a representation of its signature S for sorts in
some set T = TR as well as a representation of Σ in a monad  also called R
                           T
 over the category Set . A morphism of representations P → R consists of a
morphism f of the underlying representations of S , together with a morphism of
representations of Σ, that is compatible in a suitable sense with the translation of
sorts f . We show that the category of representations of (S, Σ) thus dened has an
initial object, which integrates the sorts freely generated by S and the terms freely
generated by Σ, typed over the sorts of S . Our denition of morphisms ensures that,
for any translation specied via the iteration principle, the translation of terms is
compatible with the translation of sorts with respect to the typing in the source
and target languages.
     To summarize, compared to Zsidó's theorem [Zsi10, Chap. 6] we consider repre-
sentations of a signature for terms over           varying    sets of sorts. However, since we
specify the set of sorts via a signature       S   and thus implement the variation of sorts
through morphisms of representations of            S,   our initial set of sorts necessarily has
inductive     structure.

     1.3.2    Integrating Reduction Rules.     In order to integrate reduction rules into our
initiality results, we dene a notion of      2signature.
                                                        A 2signature (Σ, A) is given by
a (1)signature     Σ which species the terms of a language, and a set A of inequations
over    Σ.   Intuitively, each inequation species a reduction rule, for instance the beta
rule.
   The models  or representations  of such a 2signature are built from relative
monads and modules over relative monads : given a 1signature Σ, we dene a
representation of Σ to be given by a relative monad on the appropriate functor
∆ : Set → Pre (cf. Def. 2.13) together with a suitable morphism of modules (over
relative monads) for each arity of Σ. Given a set A of inequations over Σ, we dene
a satisfaction predicate for the models of Σ; we call representation of (Σ, A) each
representation of Σ that satises each inequation of A. This predicate species a
full subcategory of the category of representations of Σ. We call this subcategory
the category of representations of (Σ, A). We prove that this category has an initial
object, which is built by equipping the initial representation of Σ  given by the
terms freely generated by Σ  with a suitable reduction relation generated by the
inequations of A.
   With this initiality theorem for (Σ, A) we obtain a new iteration principle, and
any translation specied via this principle is, by construction, compatible with the
reduction relation in the source and target languages.




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                           Initiality for Typed Syntax and Semantics         ·    19




    1.3.3     Main Theorem: Initiality for SimplyTyped Syntax with Reduction.                   Fi-
nally, we combine the above two theorems in order to obtain an initiality result
which accounts for the motivating example of Sect. 1.1. More precisely, we dene
a   2signature to be given by a typed          signature   (S, Σ)   as in Sect. 1.3.1 together a
set  A of (S, Σ)inequations analogous          to Sect. 1.3.2, specifying reduction rules.
    We dene a category of representations of        ((S, Σ), A) and prove that this category
has an initial object.        This initial representation integrates the types and terms
freely generated by        (S, Σ),   the terms being equipped with the reduction relation
generated by the inequations of          A.
    1.3.4     A Computer Implementation for Specifying Syntax and Semantics.                 Above
theorems are really meant to be implemented in a proof assistant. Such an imple-
mentation allows the specication of syntax and reduction rules via 2signatures,
yielding a highly automated mechanism to produce syntax together with certied
substitution and iteration principle.
    We prove the initiality theorem described in Sect. 1.3.2 in the proof assistant              Coq
[Coq10]. As an illustration we describe how to obtain the untyped lambda calculus
with beta reduction via initiality.
    Furthermore we formalize an instance of the theorem explained in Sect. 1.3.3,
also in      Coq.   More precisely, we dene the category of representations of the typed
signature ofPCF with inequations and prove that this category has an initial object.
Afterwards, we give a representation of this signature in the relative monad ULCβ
of the untyped lambda calculus with beta reduction, yielding a translation from
PCF     to   ULC.    Instructions on how to obtain the complete source code of our               Coq
library are available on

                     https://github.com/benediktahrens/monads/tree/thesis.

1.4     Synopsis
This thesis consists of two parts: Section 1.5.4 (Sects. 2 to 5) describes and proves
informally the theorems which constitute this thesis, whereas Exs. 5.4 (Sects. 6 to 9)
describes their implementation and verication in the proof assistant                 Coq   [Coq10].

    Section 2: CategoryTheoretic Constructions.             We recall the notions of monad
and module over a monad, together with some important constructions of mod-
ules.
    Afterwards we state equivalent denitions of monads, modules and their mor-
phisms in the style of Manes, emphasizing their              substitution structure.
    Then we recall Altenkirch et al.'s denition of         relative monads and dene suitable
morphisms for such monads.
    Finally we dene       modules over relative monads       and show that the constructions
of modules over monads carry over to modules over relative monads.

    Section 3: Simple Type Systems.           We present two initiality theorems for simple
type systems:
    In Sect. 3.2 we present Zsidó's initiality theorem [Zsi10, Chap. 6]: it characterizes
the syntax associated to a simplytyped signature              S   over a set   T   of object types
as the initial object in a category of representations of            S.


                                                 Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
20      ·     B. Ahrens




     In Sect. 3.3 we prove a variant of Zsidó's theorem which allows for representations
of a term signature over varying sets of sorts.           We introduce the notion of     typed
signature   in order to account for translations of sorts. A typed signature         (S, Σ) is
a pair consisting of a rstorderalgebraic signature S for sorts, and a higherorder
signature Σ for terms over those sorts. A representation of a typed signature (S, Σ)
is again a pair given by a representation of the sort signature S in a set T and a
                                                                              T
representation of the term signature Σ in a monad P over the category Set . We
show that the category of representations of a typed signature has an initial object.
     Finally, as an example, we use the iteration principle stemming from initiality in
order to specify a    double negation translation      from classical to intuitionistic propo-
sitional logic, viewing propositions as types via the CurryHoward isomorphism.

     Section 4: Reductions for Untyped Syntax.         We prove an initiality theorem for
untyped languages with variable binding, equipped with reduction rules.
     For the specication of such languages, we dene a notion of 2signature, i.e. a
                                    syntactic level  called 1 signature , which
signature consisting of two levels: a
species the terms of the language, and a semantic level, which species reduction
rules for those terms through inequations. A representation of such a 2signature
(Σ, A) is any representation of the underlying 1signature Σ which satises each
inequation of A.
  We dene the category of representations of (Σ, A) as the full subcategory of
representations of Σ whose objects satisfy the inequations of A. We prove that this
subcategory has an initial object, integrating the terms generated by Σ and the
reduction relation generated by the rules of A.
     As a running example we consider the 2signature of the untyped lambda calculus
with beta reduction.
     The implementation of the theorem in Coq is explained in Sect. 8.
     Section 5: Simple Type Systems with Reductions. We prove the main              result of
this thesis: we generalize the initiality result from the preceding Sect. 4 to       simply
typed   syntax with reduction rules, in a way that allows for change of object types
as in Sect. 3.3.
     More precisely, we generalize the denition of        2signature   to allow for the un-
derlying 1signature to specify a simple type system as in Sect. 3.3. Accordingly,
the denition of inequation is extended to allow for the specication of reduction
rules on such simple type systems. The main theorem of this chapter states that
the category of representations of such a 2signature has an initial object.             This
initial representation integrates the types and terms specied by the underlying 1
signature, and is equipped with the reduction relation generated by the inequations
of the 2signature.

     Section 6: Formalizing Category Theory in Coq. This chapter serves as an intro-
duction to the proof assistant Coq in general and our library of category theory used
in the following chapters in particular. We describe the formalization of basic con-
cepts such as categories, (relative) monads and modules over (relative) monads. In
the course of the chapter we also describe some of the features of Coq that we use,
such as    implicit arguments, the Program framework and coercions.
     Section 7: Formalization of Zsidó's theorem. Building upon the library presented
in Sect. 6, we describe the formalization of Zsidó's initiality theorem from Sect. 3.2


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                          Initiality for Typed Syntax and Semantics        ·      21




in   Coq.    At rst we dene a    Coq   data type of simplytyped signatures over a given
object type     T.   Afterwards we associate a category of representations to any such
signature and prove that this category has an initial object.

     Section 8: Initiality for Untyped 2Signatures, Formalized. We describe the im-
plementation in     Coq of the theorem proved informally in Sect. 4: the category of
representations of a 2signature has an initial object. The formal proof follows the
informal proof very closely; the only noteworthy dierence is that the initial ob-
ject of the underlying 1signature is constructed directly rather than through the
adjunction proved in Sect. 4.
     Finally we demonstrate how to specify the untyped lambda calculus with beta
reduction through a 2signature in our implementation.

     Section 9: A Faithful Translation of PCF to ULC.          We formalize in     Coq an instan-
ce of the main theorem of the thesis (cf. Sect. 5), for the 2signature of                  PCF,
equipped with reduction rules as presented in Fig. 7.               In particular, we explain
where we encounter diculties when using intrinsic typing in an intensional type
system.
     By representing the signature of      PCF in the monad of the untyped lambda cal-
culus, we obtain a translation from        PCF to ULC that is compatible with reductions
in the source and target languages.


1.5     Related Work
In this section we review related work, in particular in the eld of           Initial Semantics
(cf. Sect. 1.5.2), i.e. algebraic characterization of syntax (and their semantics) and
in the eld of formalization of syntax in proof assistants, cf. Sect. 1.5.3.

     1.5.1    Translations from PCF. Our main example           is given by the programming
language      PCF, introduced by Plotkin [Plo77]. This          language and its various se-
mantics have been studied extensively. The following work is not concerned with
algebraic characterization of programming languages, and thus not directly related
to this thesis; it rather answers questions that we do not (yet) consider in our
categorical setting:
     Phoa [Pho93] studies the semantic aspect of a specic translation of             PCF      to the
untyped lambda calculus, i.e. the behaviour of this translation and its compatibility
with respect to reduction in the source and target language.                The translation he
considers is also the one we specify via initiality in Sect. 9.             The main result of
this work is that this translation isadequate in the sense that a PCF programme
reduces to a natural number constant    n of PCF if and only if its translation into
the lambda calculus reduces to the corresponding church numeral cn .
  Riecke [Rie93] studies translations from PCF into itself, where source and target
are equipped with dierent reduction strategies (cf. Rem. 1.4). We do not consider
reduction strategies in this thesis.

     1.5.2    Initial Semantics.   We classify work in Initial Semantics according to the
features it covers. We are interested, in no particular order, in the following features:

Typing

Variable binding

Semantics through (in)equations

                                                Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
22       ·      B. Ahrens




Initial Semantics for untyped syntax without variable binding is a result by Birkho
[Bir35]. Goguen et al. [GTWW77] give an overview of the literature about initial
algebra and spell out explicitly the connection between initial algebras and abstract
syntax. In fact, Goguen et al. also treat the example of a programming language
with variable binding, which they call  S imple          Applicative Language    (SAL). How-
ever, they circumvent the algebraic treatment of variable binding by modelling
binding through a family of unary constructors              absx : exp → exp      where   x   varies
over a xed set of variables.

     1.5.2.1    Variable binding.    When looking for an algebraic treatment of variable
binding, the question of how to model binding arises. Some possible encodings have
already been mentioned in Sect. 1.2.3, we repeat the list  in no particular order
 for reasons of convenience:

(1) Nominal syntax using          atom   abstraction:

                                             λ : [A]T → T
(2) HigherOrder Abstract Syntax (HOAS):

                                           λ : (T → T ) → T
      and its   weak   variant:

                                           λ : (A → T ) → T
(3) Nested Data Types:

                                         λ : T (X + 1) → T (X)
In the following, the numbers in parentheses indicate the technique used for mod-
elling variable binding in the respective work, according to the list given above.
Initial Semantics for untyped syntax was presented by Gabbay and Pitts [GP99,
(1)], Hofmann [Hof99, (2)], Fiore et al. [FPT99, (3)] and Hirschowitz and Maggesi
[HM07a, (3)].
     While Gabbay and Pitts work in a        set theory   enriched with   atoms    which serve
as object level variables , Hofmann, Fiore et al. and Hirschowitz and Maggesi use
categorytheoretic      notions to formalize syntax. The nominal approach initiated by
Gabbay and Pitts is the only one among those mentioned that allows for a study
of alpha conversion. For all others the notion of alpha convertibility and syntactic
equality coincide.
     Fiore et al.'s approach is based on the notion of signature functor and         Σmonoid,
where the central concept of substitution is expressed in terms of strengths. Hir-
schowitz and Maggesi model substitution through monads, following Altenkirch
and Reus' (cf. [AR99]) characterization of the untyped lambda calculus as a monad
on the category of sets.          The connection between those two approaches is made
precise in Zsidó's PhD thesis [Zsi10] in form of adjunctions between the respective
categories of models.
     Later Gabbay and Hofmann [GH08] exhibit the relation between nominal tech-
niques and presheaves, showing that through the nominal approach one considers
in fact presheaves      F   that preserve pullbacks of monomorphisms, i.e.           presheaves
that are stable under intersection,        F (X ∩ Y ) = F X ∩ F Y .
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                          Initiality for Typed Syntax and Semantics          ·    23




  Fiore et al.'s approach was extended by Fiore [Fio02] to the simplytyped lambda
calculus, and for general simplytyped syntax by Miculan and Scagnetto [MS03,
(2)]. Both use an encoding of binding via nested data types. The relation to Higher
Order Abstract Syntax  as terms with holes  is made precise in the latter
work [MS03, Proposition 1]. Hirschowitz and Maggesi's approach was generalized
to simplytyped syntax in Zsidó's thesis [Zsi10]. It was also generalized to account
for more general term formers such as explicit attening            µ:T ◦T →T          [HM12].
  Some of the mentioned lines of work have been extended to integrate                    semantic
aspects   in form of reduction relations on terms into initiality results:

  1.5.2.2     Incorporating Semantics.       Ghani and Lüth [GL03] present rewriting for
algebraic theories without variable binding; they characterize equational theories
(with a    symmetry rule) resp. rewrite systems (with reexivity and transitivity rule,
but without     symmetry ) as coequalizers resp. coinserters in a category of monads
on the    categories Set resp. Pre.
  Fiore and Hur [FH07] have extended Fiore's work to secondorder universal
algebras, thus integrating semantic aspects in form of               equations into initiality
results. In particular, Hur's thesis [Hur10] is dedicated to            equational systems for
syntax with variable binding. In a Further research section [Hur10, Chap. 9.3],
Hur suggests the use of preorders, or more generally, arbitrary relations to model
in equational   systems.
  Hirschowitz and Maggesi [HM07a] prove initiality of the set of lambda terms
modulo beta and eta conversion in a category of              exponential monads. In an un-
published paper [HM07b] they introduce the notion of             halfequation and equation
 as a pair of parallel halfequations  that we adopt in this thesis. However,
we reinterpret a pair of parallel halfequations as an          in equation   rather than as an
equation. Accordingly, we use preorders to model semantic aspects of syntax. This
emphasizes the    dynamic    viewpoint of reductions as      directed   equalities  or      rewrite
rules    rather than the    static,   mathematical viewpoint one obtains by considering
symmetric relations.
  However, we consider not (traditional) monads but instead              relative   monads  on
the appropriate functor      ∆ : Set → Pre      (cf. Def. 2.13)  as dened by Altenkirch
et al. [ACU10], that is, monads with dierent source and target categories:                       we
consider    variables   as elements of unstructured sets, whereas the set of           terms     of a
language carries structure in form of a reduction relation. In our approach variables
and terms thus live in     dierent    categories, which is realized mathematically through
the use of relative monads instead of regular monads.
  T. Hirschowitz [Hir] denes a category        Sig of 2signatures for simplytyped syntax
with reductions, and constructs an adjunction between          Sig and the category 2CCCat
of small cartesian closed 2categories. He thus associates, to any 2signature, a 2
category of types and terms satisfying a universal property. His approach diers
from ours in the way in which variable binding is modelled: Hirschowitz encodes
binding in a HigherOrder Abstract Syntax (HOAS) style through exponentials.
Reduction relations are expressed by the existence of 2cells.

  1.5.3     Formalization of Syntax.       The implementation and formalization of syntax
                                                                                         +
has been studied by a variety of people. The PoplMark challenge [ABF 05] is a
benchmark which aims to evaluate readability and provability when using dierent

                                                Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
24       ·      B. Ahrens




techniques of variable binding. However, the benchmark only concerns           one specic
language, not arbitrary syntax specied by a signature.            The technique we use,
called   Nested Abstract Syntax,       is used in a partial solution by Hirschowitz and
Maggesi [HM10b], but was proposed earlier by others, see e.g. [BM98, AR99]. The
use of   intrinsic typing    by dependent types of the metalanguage was advertised in
[BHKM11].
     During our work we became aware of Capretta and Felty's framework for rea-
soning about programming languages [CF09].             They implement a tool  also in
the   Coq    proof assistant  which, given a signature, provides the associated ab-
stract syntax as a data type dependent on the object types, hence intrinsically
typed as well. Their data type of terms does not, however, depend on the set of
free variables of those terms. Variables are encoded with de Bruijn indices. There
are two dierent constructors for free and bound variables which serve to control
the binding behaviour of object level constructors. In our theorem, there is only
one constructor for (free) variables, and binding a variable is done by removing it
from the set of free variables.        Capretta and Felty then add a layer to translate
those terms into syntax using named abstraction, and provide suitable induction
and recursion principles. However, they do not consider         semantic   aspects, such as
reduction rules, in their work.
     The tool   Ott [SNO+ 10] allows the specication of syntax and reduction rules, even
for polymorphic type systems, in a systemindependent ASCII le with subsequent
translation into several dierent formal systems, including      Coq, Isabelle [Pau88] and
others. However, no algebraic characterization of the produced syntax is given.

     1.5.4   Published Work.     This thesis is partly based on the following articles:

     Initial Semantics for higherorder typed syntax in Coq (with J. Zsidó) [AZ11].
The content of this article corresponds to the contents of Sect. 3.2 and Sect. 7.

     Extended Initiality for Typed Abstract Syntax [Ahr12].
The content of this article corresponds to the contents of Sect. 3.3 and Sect. 3.4.

     Modules over relative monads for syntax and semantics [Ahr11].
The content of this article corresponds to the contents of Sect. 4 and Sect. 8.



2.    CATEGORYTHEORETIC CONSTRUCTIONS
In this chapter, we rst present some basic categorytheoretic denitions (Sect. 2.1).
Afterwards, we review two dierent denitions of monads and modules over monads
(cf. Sects. 2.2 and 2.3). Finally, we present relative monads and dene colax mor-
phisms of relative monads as well as modules over relative monads (cf. Sect. 2.4).


2.1     Categories, Functors & Transformations
In order to x notations, we state some basic denitions of category theory, in
particular those of category, functor and natural transformation. The examples we
give in this section are used in later chapters. The reader might want to skip this
section  throughout the thesis we link back to the denitions and examples where
necessary.
     The present section is not meant to constitute an introduction to category theory,
nor does it dene     all   of the concepts we use in the course of this work. For both an

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                            Initiality for Typed Syntax and Semantics         ·     25




introduction to category theory as well as a reference for notions whose denitions
are not given in this thesis, we refer to Mac Lane's book [ML98].

    2.1.1    Two Denitions of Categories
    Denition 2.1      (Category, Code 6.3).       A    category C   is given by

a class  which we will also call        C  of objects,
for any two objects      c and d of C , a class of morphisms, written C(c, d),
for any     object c of C , a morphism idc ∈ C(c, c) and

for any     three objects c, d, e of C , a composition operation

                                (_ ◦ _)c,d,e : C(d, e) × C(c, d) → C(c, e)
such that the composition is associative and the morphisms of the form                        idc   for
                                                                                               3
suitable objects       c   are left and right neutral with respect to this composition :

        ∀a b c d : C, ∀f : C(a, b), g : C(b, c), h : C(d, e), (h ◦ g) ◦ f = h ◦ (g ◦ f )
        ∀c d : C, ∀f : C(c, d), idd ◦ f = f       and    f ◦ idc = f .
We also write        f :c→d      for a morphism    f ∈ C(c, d).
    Remark 2.2.        We omit a fth condition stating that the classes of morphisms are
pointwise disjoint. This condition is automatically satised when implementing the
morphisms of a category as a dependent type of an intensional type theory, which
we do in Sect. 6.

    Remark 2.3 ((Equivalent Def. of Category)).             Equivalently to Def. 2.1, a category
C   is given by

a class     C0    of objects and a class   C1   of morphisms,

two maps denoting the source and target object of any morphism,

                                          src, tgt : C1 → C0 ,
a partially dened composition function

                                       (_ ◦ _) : C1 × C1 → C1 ,
    such that   g ◦ f is dened only for composable morphisms f and g , i.e. for mor-
    phisms   f and g such that tgt(f ) = src(g)  in which case we require that
    src(g ◦ f ) = src(f ) and tgt(g ◦ f ) = tgt(g) ,
an identity morphism for each object, i.e. a map

                                             id : C0 → C1 ,
    such that      src(id(c)) = tgt(id(c)) = c    and

properties analogous to those of the preceding denition. The associative law,
    e.g., reads as

     ∀f g h : C1 , tgt(f ) = src(g) =⇒ tgt(g) = src(f ) =⇒ (h ◦ g) ◦ f = h ◦ (g ◦ f ) .

3 We omit the object parameters from the composition operation, since those are deducible from

the morphisms we compose. This omission is done in our library as well, via        implicit arguments
(cf. Sect. 6.2).

                                                   Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
26      ·         B. Ahrens




While the two denitions of categories of Def. 2.1 and of Rem. 2.3 are equivalent,
they both have some advantages and inconveniences when implementing them in a
dependent type theory such as                       Coq.      We expand on these dierences in Sect. 6.3.1.

     Denition 2.4.             The category            Set has sets as objects. Morphisms from a set A
to a set  B are the             total maps from           A to B , together with the usual composition of
maps.

   Given a category C , a morphism f : c → d from object c to object d is called
invertible, if there exists a left and rightinverse g : d → c, that is, a morphism
g : d → c such that g ◦ f = idc and f ◦ g = idd . In this case the objects c and d are
called isomorphic.
   The following universal property plays a central rôle in this thesis:

     Denition 2.5. Let C be a category. The object c of C is called initial                                             if there
exists precisely  one morphism id : c → d in C to any object d of C .
     Any two initial objects of a category                         C    are canonically isomorphic. We usually
do not distinguish canonically isomorphic objects of a category, which explains the
(standard) use of the denite article. Whenever it exists, we also write                                               0C    or
simply      0,   when the category in question can be deduced from the context  for
the initial object of               C.   The dual concept is that of a                    terminal        object:

     Denition 2.6. Let C be a category. The object d of C is called terminal                                            if there
exists precisely  one morphism tc : c → d in C from any object c of C .
     Example 2.7.              The empty set is initial in the category                         Set   of sets. The singleton
set is terminal in             Set.
     Later we also use the following categories:

     Denition 2.8.             The category            Pre of preorders has, as objects, sets equipped with
a preorder, and, as morphisms between any two preorders                            A and B , the monotone
functions from             A   to   B.
     Denition 2.9.             The category            wPre has, as objects, sets equipped with a preorder,
and, as morphisms between any two preordered sets                          A and B , all settheoretic maps
from    A   to    B,      not necessarily monotone.

     Example 2.10. Any set T can be regarded as                                    a   discrete       category, with objects
the elements of  T , and just identity morphisms.
     Notation 2.11          (Product, Coproduct).                      We refer to Mac Lane's book [ML98] for
the denition of product and coproduct. Whenever they exist, we write                                                  a×b   for
the product of objects                   a    and   b   of   C,   and   a+b        for the coproduct.               Notation for
arrows is informally explained in the following diagrams:


                               a                         a×b             a
                                                                             inl   / a+b o      inr
                                                                                                      b        a+b
                      f                  g
                            (f,g)                         f ×k                         [f,h]                    f +k
                                                                             f                   h
                                                                                                         
                 co   π1
                            c×d          π2
                                              /d         c×d                             c                     c+d

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                Initiality for Typed Syntax and Semantics              ·   27




        Functors & Natural Transformations. Given two categories C and D, a
    2.1.2
functorF : C → D maps objects of C to objects of D, and morphisms of C to
morphisms of D , while preserving source and target as well as composition and
identity:

    Denition 2.12.        A functor      F    from   C   to   D   is given by

a map      F :C→D          on the objects of the categories involved and

for any pair of objects         (c, d)   of   C,   a map

                                    F(c,d) : C(c, d) → D(F c, F d) ,
such that

∀c : C, F (idc ) = idF c and
∀c d e : C, ∀f : c → d, ∀g : d → e, F (g ◦ f ) = F g ◦ F f .

Here we use the same notation for the map on objects and that on morphisms. For
the latter we also omit the subscript  (c, d) as                  implicit   arguments.

  Denition 2.13 (Functor ∆ : Set → Pre and Forgetful Functor). We call ∆ :
Set → Pre the functor from sets to preordered sets which associates to each set X
the set itself together with the smallest preorder, i.e. the diagonal of X ,

                                              ∆(X) := (X, δX ).
In other words, for any      x, y ∈ X we have xδX y if and only if x = y . The functor
∆ : Set → Pre      is afull embedding, i.e. it is fully faithful and injective on objects.
    In the other   direction we have a forgetful functor U : Pre → Set which maps any
preordered set     (X, ≤) to the set X . We have U ◦ ∆ = IdSet .
    Denition 2.14        (Natural Transformation).                 Given two functors      F, G : C → D,   a
natural transformation           γ:F →G         (also written          γ : F ⇒ G)   is given by a family of
morphisms

                                               γc : D(F c, Gc)
indexed by objects of        C   such that, for any morphism                f :c→d     in   C,   the following
diagram commutes:


                                                Fc
                                                          γc
                                                                / Gc

                                               Ff                   Gf
                                                                 
                                               Fd               / Gd
                                                          γd

    Denition 2.15 (Adjunction).               Let    C   and   D   be categories. An adjunction from
C   toD is given by
a functor   F : C → D,
a functor   G : D → C,
a natural transformation           η : IdC → G ◦ F , called unit, and
a natural transformation            : F ◦ G → IdD , called counit,

                                                          Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
28      ·        B. Ahrens




such that the transformations
                               ηG              G               Fη               F
                             G −→ GF G −→ G ,                F −→ F GF −→ F
both are the identity transformation.                  We write       F a G          for such an adjunction,
leaving the unit and counit implicit.

     Remark 2.16.         The functors     F   and   G     as above are adjoint if and only there is a
family of bijections

                                   ϕ = ϕc,d : D(F c, d) ∼
                                                                                 
                                                        = C(c, Gd)
indexed by objects         c, d ∈ C ,   which is natural in both            c   and   d.
     Denition 2.17       (Coreection).         Let   F : C → D            be an embedding, that is, a
faithful functor which is injective on objects  e.g., the inclusion of a subcategory.
Then    F     is a   coreection   if it has a right adjoint.

     The following lemma gives an example of a coreection:

  Lemma 2.18: The forgetful functor U : Pre → Set is right adjoint to the diago-
nal functor ∆ : Set → Pre:
                                                       ∆
                                                                %
                                         Set e         ⊥            Pre ,
                                                       U

that is, the embedding ∆ : Set → Pre is a coreection. We denote by ϕ the family
of isomorphisms
                       ϕX,Y : Pre(∆X, Y ) =∼ Set(X, U Y ) .
We omit the indices of ϕ whenever they can be deduced from the context.
Proof.       The unit is given by a family of identity maps             ηX := idX : Set(X, U ∆X).
The counit is given by a family of maps                    Y : Pre(∆U Y, Y ) whose carrier map on
UY     is the identity map on        UY .
     We later use the following result about left adjoints:

   Lemma 2.19 (Left adjoints are cocontinuous): Left adjoints are cocontinuous,
i.e. commute with colimits. In particular, the image of an initial object under a left
adjoint is initial.
For the proof we refer to Mac Lane's book [ML98, V.5.Thm.1].

     2.1.3     More Examples, Notations.            The following categories and functors will ap-
pear in dierent places throughout the thesis.                       Again, the reader may skip these
examples for the moment; we will point to the denitions from the place where they
are used.

     Denition 2.20                            C be a category and T be a set, i.e.
                          (Category of Families).            Let
a discrete category (cf. Ex. 2.10). We denote by C T the functor category, an object
of which is a T indexed family of objects of C . Given two families V and W , a
morphism f : V → W is a family of morphisms in C ,

                                     f : t 7→ f (t) : V (t) → W (t) .
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                  Initiality for Typed Syntax and Semantics                       ·      29




We write    Vt := V (t) for objects and                morphisms. Given another category                      D       and a
functor   F : C → D, we denote by F T                  the functor dened on objects and morphisms
as

                               F T : C T → DT ,
                                                                              
                                                             f 7→ t 7→ F (ft ) .
     Remark 2.21.    Given a set       T,       the adjunction of Lem. 2.18 induces an adjunction

                                                        ∆T
                                                                        &
                                      SetT f             ⊥                  PreT .
                                                        UT

     Denition 2.22 (Retyping Functor).                   Let   T       and      T0   be sets and   g : T → T0         be a
map. Let    C be a cocomplete category.                 The map             g    induces a functor
                                            0
                                   g∗ : C T → C T ,            W 7→ W ◦ g .
The    retyping functor associated to g : T → T 0 ,
                                                                    0
                                                 ~g : C T → C T ,
is dened as the left Kan extension operation along                              g , that is, we have an adjunction
                                                         ~
                                                         g

                                           T
                                                                    &        0
                                        C f              ⊥              CT        .                                   (2.1)

                                                         g∗

     Remark 2.23 (Retyping Functor Explicitly, Code 6.6).                               In the context of Def. 2.22,
we dene the functor
                         0                                                                     a
          ~g : C T → C T ,         X = t 7→ Xt            7→     ~g (X) := t0 7→                           Xt .
                                                                                          {t | g(t)=t0 }

In particular, for any            V ∈ CT     considered as a functor  we have a natural
transformation

                               V ⇒ ~g V ◦ g : T → C
                                          `
given pointwise by the morphism Vt →        {s|g(s)=g(t)} Vs in the category C . Put
                             0                                   T
dierently, the map g : T → T induces an endofunctor ḡ on C       with object map

                                                ḡ(V ) := ~g (V ) ◦ g
and we have a natural transformation                   ctypethe unit of the adjunction of Disp. (2.1),
                                      ctype : Id ⇒ ḡ : C T → C T .
     Remark 2.24.    One can interpret the map                   g : T → T0             as a translation of object
sorts and the functor        ~g   as a retyping functor which changes the sorts of contexts
and terms (or more generally, models of terms) according to the translation of
sorts. The monads we are interested in are monads over some category                                         SetT      and
our monad morphisms are over retyping functors. In Sect. 3 we interpret the syntax
of a language   P   over a set of types            T   as a monad            P    over the category     SetT . Given
another language     Q       over a set of types          U,   we consider a translation               from P to Q

                                                          Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
30      ·        B. Ahrens




to be a translation of object types                 g : T → U and a colax monad morphism P → Q
over the retyping functor                 ~g : SetT → SetU (cf. Def. 2.38).
     Remark 2.25 (about maps                     on coproducts and pattern matching).                  In the proof
assistant  Coq we implement                      retyping (cf. Rem. 2.23) via an inductive family, cf.
Code 6.6.        In this context, passing from the left to the right in the adjunction
isomorphism
                                                  0
                                              C T (~g V, W ) ∼
                                                             = C T (V, g ∗ W )
is done by precomposing with                     pattern matching on the constructor ctype, cf. Sect. 9.6.
     Denition 2.26 (Pointed index sets). Given a category C , a set T                                and a natural
number    n, we denote by CnT the category with, as objects, diagrams                                 of the form

                                                            t     V
                                                       n→T →C ,
written     (V, t1 , . . . , tn )   with      ti := t(i).       A morphism      h   to another such        (W, t) with
the same pointing map                     t   is given by a morphism                h : V → W         in    C T . Note
that there is are no morphisms between families with dierent points, that is,
CnT ((V, t), (V 0 , t0 )) = ∅        if   t 6= t0 .   Any functor         F : C T → DT       extends to    Fn : CnT →
DnT via
                                     Fn (V, t1 , . . . , tn ) := (F V, t1 , . . . , tn ) .
     Remark 2.27.          The category             CnT consists of T n copies of C T , which do not in-
teract. Due to the markers                      (t1 , . . . , tn ) we can act dierently on each copy, cf.,
e.g., Defs. 2.57 and 2.59.                    The reason why we consider categories of this form is
explained at the beginning of Sect. 3.3 and in Rem. 3.37.

     Retyping functors generalize to categories with pointed indexing sets; when
changing types according to a map of types                                g : T → U,         the markers must be
adapted as well:

     Denition 2.28. Given a map of sets g : T → U , by postcomposing the pointing
map with    g , the retyping functor generalizes to the functor
                        ~g (n) : CnT → CnU , (V, t) 7→ ~g V, g∗ (t) ,
                                                                   

where    g∗ (t) := g ◦ t : n → U .
     Finally there is also a category where families of objects of                             C   over dierent in-
dexing sets are mixed together:

   Denition 2.29. Given a category C , we denote by T C the category where an
object is a pair(T, V ) of a set T and a family V ∈ C T of objects of C indexed by
T . A morphism (g, h) to another such (T 0 , W ) is given by a map g : T → T 0 and a
                               T
morphism h : V → W ◦ g in C , that is, a family of morphisms in C , indexed by T ,

                                                      ht : Vt → Wg(t) .
Suppose      C   has an initial object, denoted by                    0C . Given n ∈ N, we call n̂ = (n, k 7→
0C )   the object of       TC       that associates to any            1 ≤ k ≤ n the initial object of C . We
call T Cn the      slice category             n̂ ↓ T C .   An object of this category consists of an object
(T, V ) ∈ T C       whose indexing set of types                     T   is pointed   n   times, written    (T, V, t),
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                     Initiality for Typed Syntax and Semantics                ·      31




where      t is     a vector of elements of  T of length n. A morphism (g, h) : (T, V, t) →
(T 0 , V 0 , t0 )   is a morphism (g, h) : (T, V ) → (T 0 , V 0 ) as above, such that t0 = t ◦ g .
   We call T Un : T Cn → Set the forgetful functor associating to any pointed family
(T, V, t1 , . . . , tn ) the indexing set T . Note that for a xed set T , the category CnT
(cf. Def. 2.26) is the bre over T of this functor.

   Remark 2.30            (Picking out Sorts).            Let      1 : T Cn → Set     denote the constant func-
tor which maps objects to the terminal object of the category                                         Set. A natural
transformation     τ : 1 → T Un associates                         to any object           (T, V, t) of the category
T Cn an element of T . Naturality imposes                          that   τ (T 0 , V 0 , t0 ) = g (τ (T, V, t)) for any
(g, h) : (T, V, t) → (T 0 , V 0 , t0 ).
   Notation 2.31.               Given a natural transformation                 τ : 1 → T Un         as in Rem. 2.30,
we write

                                        τ (T, V, t) := τ (T, V, t)(∗) ∈ T ,
i.e. we omit the argument                ∗ ∈ 1Set    of the singleton set.

   Example 2.32.               For    1 ≤ k ≤ n, we denote by k : 1 ⇒ T Un : T Cn → Set                            the
natural transformation such that               k(T, V, t) := t(k).
2.2     Monads & Modules
We state the widely known denition of monad and the less known denition of
module over a monad,                   together with their respective morphisms.                      Modules have
been used in the context of Initial Semantics by Hirschowitz and Maggesi [HM07a,
HM10a] and Zsidó [Zsi10]. The monad morphisms we are interested in are, more
precisely,        colax   monad morphisms, see, e.g., Leinster's book [Lei04].

   2.2.1       Denitions
   Denition 2.33              (Monad).      A    monad T          over a category     C   is given by

a functor           T :C→C           (which we denote by the same name as the monad),

a natural transformation                  η : IdC → T and
a natural transformation                  µ:T ◦T →T
such that the following diagrams commute:


                          T
                                  Tη
                                         / T2 o     ηT
                                                               T              T3
                                                                                      µT
                                                                                             / T2
                                             µ                              Tµ                   µ
                                 id
                                         #  {
                                                     id                                        
                                          T                                   T2             / T.
                                                                                       µ

   Example 2.34               (List Monad).        The functor         [_] : Set → Set       which to any set        X
associates the set of nite lists over                    X,   is equipped with a structure as monad by
dening       η     and   µ   as singleton list and attening, respectively:

                                                  ηX (x) := [x]        and

                                                               
µX      [x1,1 , . . . , x1,m1 ], . . . , [xn,1 , . . . , xn,mn ] = [x1,1 , . . . , x1,m1 , . . . , xn,1 , . . . , xn,mn ]

                                                               Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
32      ·     B. Ahrens




     Remark 2.35 (Kleisli Operation (Monadic Bind)). Given a monad (T, η, µ) on
the category  C , the Kleisli operation σ is dened, for any a, b ∈ C and f ∈ C(a, T b),
by setting

                                  σa,b : C(a, T b) → C(T a, T b) ,
                                                   f 7→ µb ◦ T f .
Indeed, a monad       (T, η, µ)   can equivalently be dened as a triple                 (T, η, σ)   with an
adapted set of axioms, see Def. 2.65. We often leave the object arguments                            a   and   b
implicit, i.e. we write   σ(f ) := σa,b (f ).
     Example 2.36    (Monadic Syntax, untyped).                       Syntax as a monad (in form of a
Kleisli triple) was presented by Altenkirch and Reus [AR99]: consider the syntax of
the untyped lambda calculus    ULC         as given in Ex. 1.2 in Sect. 1.2.1. As mentioned
there, the map       V 7→ ULC(V ) is       functorial, its map on morphisms is given by
renaming of free variables. This functor                  is equipped with a monad structure by
dening η as variableasterm operation

                                   ηV (v) := Var(v) ∈ ULC(V )
and the multiplication    µ : ULC ◦ ULC → ULC as attening which, given a term of
ULC     with terms of  ULC(V ) as variables, returns a term of ULC(V ) by removing
a    layer of intermediate Var constructors. These denitions turn (ULC, η, µ) into
a    monad on the category Set. The Kleisli operation associated to this monad
corresponds to simultaneous substitution [AR99].

     Example 2.37    (Monadic Syntax, typed).                     Consider the syntax of the simply
typed lambda calculus as dened in Ex. 1.3. The map

                        TLC : SetTTLC → SetTTLC ,                  V 7→ TLC(V ) ,
associating to any set family        V   the family of lambda terms with free variables in
V,    is the object map of a functor. Similarly to the untyped lambda calculus (cf.
Ex. 2.36), the natural transformations             η : Id → TLC             and   µ : TLC ◦ TLC → TLC     are
dened as variableasterm operation and attening, respectively. These denitions
turn   (TLC, η, µ)   into a monad on the category                  SetTTLC .
     Our denition of   colax   monad morphisms and their                   transformations   is taken from
Leinster's book [Lei04]:

 Denition 2.38 (Colax Monad Morphism).                               Let   (T, η, µ) be a monad on the
categoryC and (T 0 , η 0 , µ0 ) be a monad on the                     category   D. A colax morphism of
monads (C, T ) → (D, T 0 ) is given by
a functor     F :C→D       and

a natural transformation          γ : F T → T 0F             as in



                                              C
                                                          T        /C

                                          F          {       γ         F

                                                                    
                                              D                    /D
                                                          0
                                                     T
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                Initiality for Typed Syntax and Semantics                     ·    33




such that the following diagrams commute:


                  FTT
                             γT
                                  / T 0F T        γ
                                                      / T 0T 0F                  F
                                                                                            η0 F
                 Fµ                                           µ0 F              Fη
                                                                                              "
                     FT                                / T 0 F,                  FT            / T 0 F.
                                       γ                                                   γ

    From now on we simply say monad morphism over                                   F   when speaking about a
colax monad morphism with underlying functor                             F.
    Denition 2.39    (Composition of Monad Morphisms).                                   Suppose given a monad
morphism as in Def. 2.38. Given a third monad     (T 00 , η 00 , µ00 ) on category E and a
                      0  0    0 0   0      00 00   00
monad morphism (F , γ ) : (T , η , µ ) → (T , η , µ ), we dene the composition of
             0   0
(F, γ) and (F , γ ) to be the monad morphism given by the pair consisting of the
          0
functor F F and the transformation

                                           F 0γ                    γ0F
                              F 0F T              / F 0T 0F              / T 00 F 0 F .

The verication of the necessary commutativity properties is done  for the equiva-
lent denition given in Def. 2.69  in the              Coq library, cf. colax_Monad_Hom_comp
.

    Denition 2.40    (Transformation).               Given two morphisms of monads

                               (F, γ), (F 0 , γ 0 ) : (C, T ) → (D, T 0 ) ,
a   transformation (F, γ) → (F 0 , γ 0 )        is given by a natural transformation                      β : F ⇒ F0
such that the following diagram commutes:


                                            FT
                                                        γ
                                                                  / T 0F

                                           βT                            T 0β

                                                                      
                                           F 0T                   / T 0F 0.
                                                       γ0

    A   2category   is a category with morphisms between morphisms. We refer to
Mac Lane's book [ML98] for the denition.

    Denition 2.41        (2Category of Monads, [Lei04]).       We call Mndcolax the 2
category an object of which is a pair       (C, T ) of a category C and a monad T on
C . A morphism to another object (D, T 0 ) is a colax monad morphism (F, γ) :
(C, T ) → (D, T 0 ). A 2cell (F, γ) ⇒ (F 0 , γ 0 ) is a transformation.
    Notation 2.42.        For any category        C , we write IdC         for the object          (C, Id) of Mndcolax
.

    We are interested in       modules over monads.                    These are particular monad mor-
                                                                                                    4
phisms whose codomain is the identity monad on some category . Modules and,


4 The characterization of modules over monads as particular colax monad morphisms is due to an

anonymous referee, whom I hereby thank for his helpful comments.


                                                        Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
34      ·      B. Ahrens




more specically, their morphisms, capture the distributivity of substitution over
the constructors of a language, cf. Ex. 2.47 and Ex. 2.74.

  Denition 2.43 (Module over a Monad). Given categories C and D and a monad
T  on C , a module over T with codomain D (or T module towards D ) is a colax
monad morphism (M, γ) : (C, T ) → (D, IdD ) from T to the identity monad on D .
Given parallel T modules M and N , a morphism of modules from M to N is a
transformation from M to N as in Def. 2.40. We denote the category of T modules
towards D by
                                                          
                    Mod(T, D) := Mndcolax (C, T ), (D, Id) .
Before giving some examples of modules over monads, we state a more explicit
denition of modules:

     Remark 2.44    ((Modules and their Morphisms, explicitly [HM07a])).                    By unfold-
ing the preceding denition and simplifying, we obtain that a                   T module towards
D    is a functor   M :C →D       together with a natural             transformation σ : M T → M
such that the following diagrams commute:


                            MTT
                                     σT       / MT               M
                                                                       id
                           Mµ                    σ          Mη
                                                                          "
                             MT               / M,            MT            / M.
                                      σ                               σ

Such a module can hence be regarded as a kind of generalized monad over a functor
that is not necessarily an endofunctor; indeed, this is our intuition behind mod-
ules. In particular, every monad gives rise to a module over itself, the                   tautological
module      (cf. Def. 2.48). Furthermore, the category of modules                  Mod(T, D) allows for
products, provided the target category     D is equipped with a product.
     A morphism of      T modules from (M, σ) to (M 0 , σ 0 ) then is given by              a natural
transformation      β : M ⇒ M 0 such that the following diagram commutes:

                                          MT
                                                     βT
                                                          / M 0T

                                          σ                      σ0
                                                             
                                          M                / M 0.
                                                     β

We anticipate the constructions of the next section by giving some examples of
modules:

     Example 2.45    (Tautological Module, Ex. 2.36 cont.).                  Any monad     T on a cat-
egory   C can be     considered as a module over itself, the                  tautological module (cf.
Def. 2.48).     In particular, the monad of the untyped                     lambda calculus ULC (cf.
Ex. 2.36) is a    ULCmodule      with codomain           Set.
     Example 2.46.     The map

                                    ULC0 : V 7→ ULC(V 0 ) ,
with   V 0 := V + 1, inherits the structure of a ULCmodule from the tautological
module    ULC  we obtain the derived module (cf.  2.2.3.1) of the module ULC.
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                          Initiality for Typed Syntax and Semantics         ·       35




Also, the map

                            ULC × ULC : V 7→ ULC(V ) × ULC(V )
inherits a   ULCmodule      structure, cf. Def. 2.53.

  The constructors of our example languages are, accordingly,                morphisms of mod-
ules :
  Example 2.47      (Ex. 2.46 cont.).      The map

                          V 7→ AppV : ULC(V ) × ULC(V ) → ULC(V )
satises the diagram of Rem. 2.44 and is hence a morphism of                 ULCmodules        from
ULC × ULC     to   ULC.   The map

                              V 7→ AbsV : ULC(V 0 ) → ULC(V )
is a morphism of     ULCmodules      from   ULC0    to   ULC.   Later we consider this example
using an alternative denition of module morphism (cf. Def. 2.73) and explain in
detail the meaning of its commutative diagrams for the constructors                App    and   Abs,
cf. Ex. 2.74.

  2.2.2    Constructions on Monads and Modules.                  We present some constructions
of modules which will be used in the next section. They were previously dened in
Zsidó's thesis [Zsi10] and works of Hirschowitz and Maggesi [HM07a, HM10a].

  Denition 2.48 (Tautological Module). Given a monad (C, T ),                    we call   (T, µT )
(or simplyT ) the tautological module (T, µT ) : (C, T ) → (C, Id).
  Denition 2.49 (Constant and Terminal Module). Given a monad (C, T ) and a
category  D with an object d ∈ D, the constant functor Fd : C → D mapping any
object of C to d ∈ D and any morphism to the identity on d yields a module

                                  (Fd , id) : (C, T ) → (D, Id) .
In particular, ifD has a      terminal object     1D ,    then the constant module     (F1D , id)   is
terminal in   Mod(T, D).
  Remark 2.50. Given a monad (C, T ), a T module (M, σ) with codomain cate-
goryD and a functor F : D → E , then the pair (F ◦ M, F σ) is a T module with
codomain category E . For (M, σ) := (T, µT ) and F := Fe for some e ∈ E one
obtains the constant module as above.

  Denition 2.51 (Pullback Module).      (C, T ) and (D, T 0 ) be monads over C and
                                               Let
D, respectively. Given a morphism of monads (F, γ) : (C, T ) → (D, T 0 ) and a T 0 -
module (M, σ) with codomain E , we call pullback of M along (F, γ) the T module
(F, γ)∗ (M, σ) := (M, σ) ◦ (F, γ).
  Denition 2.52     (Module Morphism induced by a Monad Morphism).                       With the
same notation as in the previous example, the monad morphism                     (F, γ)   induces a
morphism of     T modules     which we call       γ    as well 

                               γ : (F, id) ◦ T ⇒ (F, γ)∗ (T 0 , µT 0 )


                                                 Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
36       ·      B. Ahrens




as in

                                                            (C, T )
                                           (T,µT )                           (F,γ)

                                        z                       γ                    $
                                  (C, Id)                           +3              (D, T 0 )

                                           (F,id)
                                                         $    z              (T 0 ,µT 0 )
                                                        (D, Id)                             .
Note that the above diagram can be read as a structureenriched version of the
square diagram specifying the type of                       γ   in Def. 2.38.

     Denition 2.53     (Product Module).                       Suppose the category                   D    is equipped with
a product.       Given any monad                 (C, T ),   the product of                  D    lifts to a product on the
category       Mod(T, D)    of   T modules           with codomain                D.
     2.2.3     Monads on Set Families.                We are particularly interested in monads over
families of sets and monad morphisms over retyping functors.

     2.2.3.1    Derivation.      Roughly speaking, a binding constructor makes free vari-
ables disappear.       Its inputs are hence terms with (one or more) additional free
variables compared to the output, i.e. terms in an                    extended context. Context                              ex-
tension is captured mathematically by                     derivation : let T be a set and u ∈ T                               an
                                                                        T
element of      T.   We dene     D(u)       to be     the object of Set such that

                        D(u)(u) = {∗}                 and        D(u)(t) = ∅            for      t 6= u .
                                             T
We enrich the object         V    of   Set        with respect to             u    by setting

                                                 V ∗u := V + D(u) ,
that is, we add a fresh variable of type                     u.          This yields a monad            (_)∗u   on   SetT .
     Denition 2.54     (Derivation Monad Morphism).                                  Given any monad            P   on   SetT ,
                                                                                                        ∗u
we dene a monad endomorphism on                       P over the functor V 7→ V . On a set family
V ∈ SetT       its natural transformation              γ is dened as the coproduct map
                         γV := [P (inl), η ◦ inr] : (P V )∗u → P (V ∗u ) ,                                                (2.2)

                                 ∗u          ∗u
where    [inl, inr] = id : V          →V          .

     Denition 2.55.        Given a monad              P     over  SetT and                 a   P module M ,    we call      Mu
the module obtained as the composition                           M ◦ (_)∗u .
     Example 2.56.      We consider         TLC (cf. Ex. 2.37) as the tautological module                                  over
itself. Given any element             s ∈ TTLC , the derived module with respect to s,
                                           TLCs : V 7→ TLC(V ∗s ) ,
assigns to any type family             V    the      context             the type family of terms of               TLC over
V    enriched with one additional variable of sort                            s.
     More generally, given a natural transformation as in Rem. 2.30,

                                       τ : 1 ⇒ T Un : T Setn → Set ,
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                               Initiality for Typed Syntax and Semantics         ·       37




we can derive, with respect to            τ,   any module dened on a category of the form
SetTn   for any set   T:
  Denition 2.57        (Derived Module).             Let      τ : 1 → T Un be a natural transfor-
mation.     Given a set      T   and a monad       P      on    SetTn , the functor (_)∗τ : (T, V, t) 7→
(T, V ∗τ (T,V,t) , t) is given the structure of a morphism of monads as in Disp. (2.2).
Given any P module M , we call derivation of M with respect to τ the module
M τ := M ◦ (_)∗τ .
  Remark 2.58. In the preceding denition the natural transformation τ : 1 →
T Un supplies more data than necessary, since we only evaluate it on families of sets
indexed by the xed set T . However, in Sect. 3.3 we derive dierent modules 
                             T
each dened on a category Setn with varying sets T  with respect to one and the
same natural transformation τ .

  2.2.3.2     Fibres.                                                        T , we
                           Given a typed language over a nonempty set of types
occasionally want to pick terms of a specic type  u ∈ T . Let D be a category 
                                              T
think of D as the category Set  and V ∈ D      a T indexed family, e.g., of terms
of said language. Then picking terms of type u ∈ T  corresponds to projecting to
the bre V (u).
                                                                   T
   Given a monad P on a category C and a P module M towards D , we dene the
bre module of M with respect to u ∈ T to be the module which associates the bre
M (c)(u) to any object c ∈ C . This construction is expressed via postcomposition
with a particular module: we dene the bre with respect to u ∈ T to be the monad
morphism

                                  (_)(u), id : (DT , Id) → (D, Id)
                                            

over the functor      V 7→ V (u).       Postcomposition of the module             M with this module
then precisely yields the bre module            [M ]u of M       with respect to u ∈ T . Analogously
to derivation we dene the bre with respect to a natural transformation:

  Denition 2.59 (Fibre Module).                Let   τ   be a natural transformation as in Def. 2.57.
We callbre with respect to τ the              monad morphism

                             (_)τ : V 7→ V (τV ) : (DnT , Id) → (D, Id)
over the functor      V 7→ Vτ (V ) . Given a module M towards DnT (over some monad
P ),   we call the   bre module of M with respect to τ the module [M ]τ := (_)τ ◦ M .
  Example 2.60. We consider TLC as the tautological module over itself. Given
any element t ∈ T , the bre module with respect to t, denotes the set of terms of
TLC of type t in context V :
                                       [TLC]t : V 7→ TLC(V )t .
  Example 2.61.         Consider the monad             TLC : SetTTLC → SetTTLC       of Ex. 2.37. The
two operations of derivation (cf. Ex. 2.56) and bre (cf. Ex. 2.60) can be combined,
yielding a module over           TLC   with carrier

                                  V 7→ TLCst (V ) := TLC(V ∗s )t .
This module is actually the domain module of the abstraction constructor, cf.
Ex. 2.62. The product of modules yields our nal example: for any                       s, t ∈ TTLC ,   the

                                                      Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
38      ·       B. Ahrens




domain of the application           App(s, t)      of simplytyped lambda calculus is a module
over   TLC,
                     [TLC]s;t × [TLC]s : V 7→ TLC(V )s;t × TLC(V )s .
     Example 2.62     (Ex. 2.61 cont.).         Given   s, t ∈ TTLC ,   the map

            App(s, t) : V 7→ AppV (s, t) : TLC(V )s;t × TLC(V )s → TLC(V )t
satises the diagram of the preceding denition and is hence a morphism of modules.
In the same way the constructor               Abs(s, t)   is a morphism of modules; we have

                             App(s, t) : [TLC]s;t × [TLC]s → [TLC]t
                             Abs(s, t) : [TLCs ]t → [TLC]s;t .
     The pullback operation commutes with products, derivations and bres:

     Remark 2.63.      Let    (C, P ) and (D, Q) be monads, and let ρ : P → Q be a monad
morphism. Let        M   be a    Qmodule with codomain E . Suppose T is a set, and let
u∈T      be an element       of T .

(1) More specically, let          Q   be a monad on       SetT .   Then

                                               ∗             ∗
                                             ρ (M ) = (ρ M )u .
                                                    u


(2) More specically, let          E = CT .    Then

                                              ρ∗ [M ]u = [ρ∗ M ]u .
(3) Let     N   be another    Qmodule        with codomain      E   and suppose   E   is equipped with
      a product. Then the pullback functor is cartesian:

                                        ρ∗ (M × N ) = ρ∗ M × ρ∗ N .
The rst two properties are just instances of associativity of composition of monad
morphisms.

     Remark 2.64.      In    Coq   the equality of modules is not as trivial as in informal
mathematics, since there are two dierent notions of equality:                    denitional equality,
also called     convertibility, and propositional         equality. While the latter is to be proved
by the user, the former is computed by the system and thus cannot be inuenced
by the user.
     While the above equalities of Rem. 2.63 hold propositionally (using appropri-
ate axioms, such as proof irrelevance), they do not hold denitionally. The conse-
quences of this lack of denitional equality are discussed in Sect. 7.1.2. In summary,
in our formalization, monads, modules and module morphisms behave more like in
a   bicategory    rather than in a strict 2category.


2.3    Alternative Denitions for Monads & Modules
Monads can be dened in terms of the Kleisli operation (cf. Rem. 2.35) instead of
the natural transformation             µ   of Def. 2.33.    A similar alternative denition exists
for modules.       In this section we state those alternative denitions in full detail,
for several reasons: rstly, the alternative denition of monad is wellknown for
its prominent use in the Haskell programming language. Secondly, it is also the


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                 Initiality for Typed Syntax and Semantics                ·         39




denition we chose to implement in the proof assistant                     Coq. Furthermore, it is also
this alternative denition which generalizes to                   relative monads (cf. Def. 2.75), that
is, monads that are not necessarily endofunctors.

  Denition 2.65 (Alt. Def. for Monad (Def.                   2.33), Code 6.10).           A   monad T         over
a categoryC (in Kleisli form) is given by
a map     T : C → C on the objects of C , carrying the same                   name as the monad,

for   each object c of C , a morphism ηc ∈ C(c, T c) and

for   all objects c and d of C , a Kleisli map

                                          σc,d : C(c, T d) → C(T c, T d)
such that the following diagrams commute for all suitable morphisms                              f     and    g:
                                                                                    σ (f )
          c
                 ηc
                        / Tc                Tc                              Tc                 / Td
                                                        σ (ηc )

                             σ (f )                                                               σ (g)
                f                                                          σ (σ (g)◦f )
                                                id                                           ! 
                           T d,                           * T c,                                T e.
We also refer to the Kleisli map as substitution map: when                        C     is instantiated, for
example, by the category of sets and        TX             is a set of terms with free variables in
the set   X,    then   simultaneous substitution           as Kleisli map turns            T   into a monad.
In this case the diagrams express the wellknown substitution properties [AR99].
More precisely, the rst diagram determines the value of substitution on variables,
the second diagram states that substituting each variable by itself in a term does
not change the term, and the third diagram shows how two consecutive substitu-
tions can be expressed by just one substitution. Inspired by Haskell syntax, we
frequently use the inxed symbol                  =     to denote simultaneous substitution (or
more generally, Kleisli maps): given a term                 M ∈ TX       with free variables in           X        and
f : X → TY ,        then

                                          M = f := σ(f )(M )
denotes the term obtained by replacing any free variable                      x∈X         occurring in        M     by
its image     f (x) ∈ T Y ,       yielding a term in   TY .
  The following remarks recover the denition of monad given in Def. 2.33 from
the denition of Def. 2.65.

  Remark 2.66 (Functoriality for Monads in Kleisli Form, Code 6.11). Given                                           a
monad T over C as in Def. 2.65 and a morphism f : c → d in C , we equip T with                                       a
functorial structure by setting

                                      T (f ) := liftT (f ) := σ (ηd ◦ f ) .
  Remark 2.67          (Naturality of       η and Multiplication for Monads in Kleisli form).
Given a monad in Kleisli form               T , the family of morphisms η = (ηc : C(c, T c))c∈C is
natural with respect to the functorial structure dened in Rem. 2.66. A multipli-
cation   µ : T2 → T        can be dened as substitution with identity:

                                        µc := σ(idT c ) : T T c → T c .
                                                       Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
40      ·    B. Ahrens




Naturality of   µ   is a consequence of the axioms for monads in Kleisli form. Finally,
the monad multiplication           µ   thus dened is compatible with the unit               η   in the sense
of Def. 2.33.

     Remark 2.68 (Naturality of Substitution). Given a monad in Kleisli form T                             over
C,   then its substitution σ is natural in c and d. For naturality in c we check                           that
the diagram

                                                          σc,d
                              c        C(c, T d)                     / C(T c, T d)
                                               O                        O
                          f                  f∗                         (T f )∗
                               
                              c0       C(c0 , T d)                   / C(T c0 , T d)
                                                          σc0 ,d

commutes, where       f ∗ (h) := h ◦ f .      Given      g ∈ C(c0 , T d),   we have

                                   σ(g) ◦ T f = σ(g) ◦ σ(ηc0 ◦ f )
                                                     3
                                                     = σ(σ(g) ◦ ηc0 ◦ f )
                                                     1
                                                     = σ(g ◦ f ) ,
where the numbers correspond to the diagrams of Def. 2.65 used to rewrite in the
respective step.     Similarly we check naturality in                 d.    Writing    h∗ (g) := h ◦ g ,   the
diagram


                                                          σc,d
                              d        C(c, T d)                     / C(T c, T d)

                          h              (T h)∗                         (T h)∗
                                                                      
                           d0          C(c0 , T d)                   / C(T c0 , T d)
                                                          σc0 ,d

commutes: given      g ∈ C(c, T d),       we have

                                   T h ◦ σ(g) = σ(ηd0 ◦ h) ◦ σ(g)
                                                     3
                                                     = σ(σ(ηd0 ◦ h) ◦ g)
                                                     = σ(T h ◦ g) .
     Denition 2.69 (Morphism of Monads, Alt. to Def. 2.38, Code 6.12). Let (C, T )
and   (D, T 0 ) be two monads. A colax morphism of monads τ : T → T 0 is given by
a functor    F : C → D and
for any    c ∈ C , a morphism τc : F T c → T 0 F c




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                       Initiality for Typed Syntax and Semantics                      ·            41




such that the following diagrams commute for all suitable morphisms                                          f:
                   F (σ T (f ))                                                              F ηcT
         FTc                                 / FTd                             Fc                          / FTc


         τc                                       τd                                                             τc
                                                                                          T  0
                                                                                         ηF c


                                                                                                          ! 
         T 0F c                            / T 0F d ,                                                      T 0F c .
                       T0
                   σ        (τd ◦F f )

    Remark 2.70.        Naturality of the family                    (τc )c∈C   of a colax morphism of monads
as in the preceding denition is provable from the other axioms, yielding a natural
transformation

                                                   τ : F T → T 0F .
Here we use Rem. 2.66 by considering   T and T 0 as functors. The naturality                                            of     τ   is
proved in Lemma         colax_Monad_Hom_NatTrans in the Coq library.
    Denition 2.71 (Module, Alt. to Rem. 2.44, Code                                 6.14).       Let   D   be a category.
A   module M over T with codomain D is given by
a map     M: C →D            on the objects of the categories involved and

for all   objects c, d       of   C,    a map

                                             ςc,d : C(c, T d) → D(M c, M d)
such that the following diagrams commute for all suitable morphisms                                          f    and     g:
                                         ς (f )
                            Mc                    / Md                 Mc
                                                                                       ς (ηc )

                                                        ς (g)
                             ς (σ (g)◦f )
                                                  !                           id
                                                                                          * 
                                                  M e,                                     M c.
    Remark 2.72.       Functoriality for such a module                       M      is dened similarly to that for
monads: for any morphism                    f :c→d         in   C   we set

                                    M (f ) := mliftM (f ) := ς (η T ◦ f ) .
A   module morphism             is a family of morphisms that is compatible with module
substitution:

    Denition 2.73      (Module Morphism, Alt. to Rem. 2.44, Code 6.15).                      Let M and
N   be two modules over            T     with codomain         D. A morphism of T modules from M to
N   is given by a family of morphisms                      ρc ∈ D(M c, N c) such that for all morphisms




                                                                Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
42       ·     B. Ahrens




f ∈ C(c, T d)   the following diagram commutes:

                                               ς M (f )
                                        Mc                  / Md

                                       ρc                       ρd

                                                              
                                         Nc                 / N d.
                                                N
                                               ς (f )

A module morphism           M → N also constitutes a natural transformation between
the functors    M   and    N induced by the modules, cf. Module_Hom_NatTrans.
     Example 2.74    (Ex. 2.47 cont.).      We consider Ex. 2.47 under the alternative def-
inition of module morphism. The map

                        V 7→ AppV : ULC(V ) × ULC(V ) → ULC(V )
satises the diagram of the preceding denition and is hence a morphism of                       ULC
modules from        ULC × ULC    to   ULC.    The property of being a module morphism
expresses distributivity of substitution for any substitution map                   f : X → ULC(Y ):


                     App(M, N ) = f = App(M = f, N = f ) .
Similarly, the map

                              V 7→ AbsV : ULC(V 0 ) → ULC(V )
is a morphism of     ULCmodules      from    ULC0     to   ULC.     For   f : X → ULC(Y )   as before,
the commutative diagram here expresses the equation



                             Abs(M ) = f = Abs(M = f 0 ) ,
where    f 0 : X 0 → ULC(Y 0 )    is obtained by shifting the map               f   to account for the
extended context under the binder            Abs.
     Modules on P with codomain D and morphisms between them form                          a category
called   Mod(P, D) (in the library: MOD P D), similar to the category of                   monads.


2.4    Relative Monads and Modules
The functors underlying the monads presented in the preceding section all are endo-
functors. This is enforced by the type of monadic multiplication and substitution.
Relative monads       were dened by Altenkirch et al. [ACU10] to overcome this re-
striction. One of their motivations was to consider the untyped lambda calculus
over   nite   contexts as a monadlike structure  similar to the monad structure
on the lambda calculus over arbitrary contexts exhibited by Altenkirch and Reus
[AR99].
     We review the denition of relative monads and dene suitable            colax morphisms
of relative monads.        Afterwards we dene         modules over relative monads and port
the constructions on modules over monads (cf. Sects. 2.2.2 and 2.2.3) to modules
over relative monads.


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                              Initiality for Typed Syntax and Semantics                      ·         43




  2.4.1        Denitions.       We review the denition of relative monad as given by Al-
tenkirch et al. [ACU10] and dene suitable morphisms for them. As an example
we consider the lambda calculus as a relative monad from sets to preorders, on
the functor      ∆   (cf. Def. 2.13). Afterwards we dene                 modules over relative monads
and carry over the constructions on modules over regular monads of the preceding
section to modules over relative monads.
  The denition of relative monads is analogous to that of monads in Kleisli form
(cf. Def. 2.65), except that the underlying map of objects is between                             dierent            cat-
egories.    Thus, for the operations to remain welltyped, one needs an additional
mediating functor, in the following usually called                      F,   which is inserted wherever
necessary:

  Denition 2.75 (Relative Monad, [ACU10], Code 6.16). Given categories C and
                                                    F
D and a functor F : C → D, a relative monad P : C → D on F is given by the
following data:

a map    P : C → D on the objects of C ,
for   each object c of C , a morphism ηc ∈ D(F c, P c)                    and

for   each two objects c, d of C , a substitution map

                                      σc,d : D(F c, P d) → D(P c, P d)
such that the following diagrams commute for all suitable morphisms                                   f   and    g:
                                                                                                σ (f )
Fc
            ηc
                     / Pc                Pc                                            Pc                   / Pd
                                                          σ (ηc )

                        σ (f )                                                                                    σ (g)
           f                                                                           σ (σ (g)◦f )
                     !                          id
                                                             )                                             ! 
                     Pd ,                                        Pc ,                                       Pe .
  Example 2.76         (Lambda Calculus over Finite Contexts, [ACU10]).                                   Altenkirch
et al. [ACU10] consider the untyped lambda calculus as a relative monad on the
functor    J : Finskel → Set.       Here the category      Finskel is the category of nite cardinals,
i.e. the skeleton of the category          Fin   of   nite sets and maps between nite sets.
  Remark 2.77.          Relative monads on the identity functor                        Id : C → C          precisely
correspond to monads as presented in Def. 2.65.

  Notation 2.78.            For this section we reserve the term monad for monads as
dened in Def. 2.65, and explicitly state the relative when talking about relative
monads. In later sections we sometimes omit the attribute relative and instead
refer to traditional monads (i.e. with                F = Id)     as   regular   or   plain   monads.

 Remark 2.79 (Restricting a Monad yields a Relative Monad, [ACU10]). Given
a monadT on D and a functor F : C → D, then the monad T restricts to a relative
       [    F
monad T : C → D by precomposing with F .

  Remark 2.80 (Relative Monads are functorial, Code 6.17). Given a monad P
overF : C → D and a morphism f : c → d in C , a functorial structure (rlift) for P

                                                        Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
44      ·        B. Ahrens




is dened by setting

                                   P (f ) := liftP (f ) := σ (η ◦ F f ) .
The functor axioms are easily proved from the monadic axioms.

  Remark 2.81 (Relative Monads as Monoids in a Functor Category, [ACU10]). A
monad  (T, η, µ) over a category C is the same as a monoid object in the functor
category [C, C], where the monoidal structure is given by functor composition. Al-
tenkirch et al. [ACU10] recover a similar characterization for relative monads on a
functor     F : C → D,       provided that the left Kan extension along                F,
                                            LanF : [C, D] → [D, D] ,
exists: they dene a lax monoidal structure on                     [C, D]     by

                             F
                           (· ) : [C, D] × [C, D] → [C, D]
                                             (H, G) 7→ H ·F G := LanF H ◦ G .
They then show that relative monads on                      F   correspond precisely to lax monoid ob-
jects in    ([C, D], ·F ).   Besides, they show that under some coherence conditions, this
result can be sharpened to obtain a strict monoidal structure, where relative mon-
ads correspond to proper monoids with respect to this structure. Under the same
assumptions, a relative monad                 P   on   F : C → D can          be extended to a traditional
monad       P]   on   D,   yielding an adjunction         (_)] a (_)[ .       This adjunction furthermore
is a coreection.

     Remark 2.82 (Naturality of Substitution).                    Analogously to Rem. 2.68, the sub-
stitution σ = (σc,d ) of a relative monad P on                    a functor    F :C→D       is binatural.

     We are interested in monads on the category                    Set   of sets and relative monads on
∆ : Set → Pre         as well as their relationship:

  Lemma 2.83 (Relative Monads on ∆ and Monads on Set): Let P be a relative
monad on ∆ : Set → Pre (cf. Def. 2.13). By postcomposing with the forgetful
functor U : Pre → Set we obtain a monad
                                               U P : Set → Set .
The substitution is dened, for m : X → U P Y by setting
                            U σ : m 7→ U σ ϕ−1 m
                                                 
                                                     ,
as indicated by the diagram

                       Set(X, U P Y )
                                                       Uσ           / Set(U P X, U P Y )
                                                                       O
                                  ϕ−1                                     U
                                        
                       Pre(∆X, P Y )                                / Pre(P X, P Y )
                                                        σ

making use of the adjunction ϕ of Lem. 2.18.
  Conversely, to any monad T over Set, given as a Kleisli triple, we associate
a relative monad over ∆ by postcomposing with ∆. The substitution map ∆σ is

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                        Initiality for Typed Syntax and Semantics           ·     45




dened, for m : ∆X → ∆T Y , as the following composition:

                  Pre(∆X, ∆T Y )
                                                ∆σ           / Pre(∆T X, ∆T Y )
                                                                O
                                U                               ϕ−1
                                    
                        Set(X, T Y )                         / Set(T X, T Y )
                                                 σ

The maps thus dened are object functions of an adjunction between monads on
sets and relative monads on ∆, cf. Lem. 4.5.
  The above construction actually is an instance of a more general construction:

  Lemma 2.84 (Monads from Relative Monads and conversely):                       Let F : C  D :
G be an adjunction with a family of isomorphisms
                           ϕX,Y : D(F X, Y ) ∼
                                             = C(X, GY ) : ϕ−1
                                                            X,Y .

                                         F
(1 )   Given a relative monad P : C → D with unit η and substitution σ , we dene a
       monad P + on C by setting
       P + (c) := GP c,
       ηc+ := ϕ(ηc ) : C(c, GP c) and
                                 
       σc,d
          +
             (f ) := G σ ϕ−1 (f ) .
(2 )   Let furthermore GF = Id be the identity on C . Given a monad (P, η, σ) on C ,
                                         F
       we dene a relative monad P − : C → D by setting
       P − (c) := F P c,
       ηc− := F (ηc ) and
       σc,d
          −
             := ϕ−1 σ(Gf ) .
                            

Proof.     We check the commutativity of the corresponding diagrams:

(1) for the data   (P + , η + , σ + ):
                                −1
           +
       σ (f ) ◦ ηc = G(σ(ϕ         f )) ◦ ϕ(ηc ) = ϕ(σ(ϕ−1 f ) ◦ ηc ) = ϕϕ−1 f = f
         + +                −1
       σ (ηc ) = G(σ(ϕ         (ϕ(ηc )))) = G(σ(ηc )) = G id = id
       

                           σ + (g) ◦ σ + (g) = Gσϕ−1 g ◦ Gσϕ−1 f
                                             = G σ(ϕ−1 g) ◦ σ(ϕ−1 f )
                                                                     

                                             = G σ(σ(ϕ−1 g) ◦ ϕ−1 f )
                                                                     

                                             = G σ(ϕ−1 (G(σ(ϕ−1 g)) ◦ f ))
                                                                                

                                             = σ + (σ + (g) ◦ f )
(2) for the data  (P − , η − , σ − ):
           −
       σ (f ) ◦  ηc−
                   = ϕ−1 (σ(Gf )) ◦ F ηc = ϕ−1 (σ(Gf ) ◦ ηc ) = ϕ−1 (Gf ) = f
         − −        −1
       σ (ηc ) = ϕ    (σ(Gηc− )) = F P C ◦ F (σ(GF ηc )) = F P c ◦ F (σ(ηc )) = F P c ◦
        F id = id



                                                 Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
46      ·       B. Ahrens




      
                                                                        
                                  σ − (σ − g ◦ f ) = ϕ−1 σ G(σ − g ◦ f )
                                                                        
                                                   = ϕ−1 σ Gσ − g ◦ Gf
                                                 = ϕ−1 (σ(σGg ◦ Gf ))
                                                 = ϕ−1 (σGg ◦ σGf )
                                                 = F ◦ F (σGg ◦ σGf )
                                                 = F ◦ F σGg ◦ F σGf
                                                 = F ◦ F σGg ◦ F ◦ F σGf
                                                 = ϕ−1 σGg ◦ ϕ−1 σGf
                                                 = σ− g ◦ σ− f


This construction is functorial, and yields an adjunction between a category of
monads on       C   and relative monads on        F.    Details will be reported elsewhere.

     Example 2.85       (Lambda Calculus as Relative Monad on                ∆).     Consider the set of
all lambda terms indexed by their set of free variables as dened in Ex. 1.2. We
write   λM     and   MN     for   Abs M   and   App M N ,     respectively. We equip each         ULC(V )
with a preorder taken as the reexivetransitive closure of the relation generated
by the rule

                                          (λM )N ≤ M [∗ := N ]
and its propagation into subterms. This denes a monad                        ULCBETA         from sets to
preorders over the functor          ∆,
                                                          ∆
                                           ULCβ : Set → Pre.
The family      η ULC    is given by the constructor       Var,    and the substitution map
                                                                                         
                    σX,Y : Pre ∆(X), ULCβ (Y ) → Pre ULCβ (X), ULCβ (Y )
is given by captureavoiding simultaneous substitution.                       Via the adjunction of
Lem. 2.18 the substitution can also be read as
                                                                   
                     σX,Y : Set X, ULC(Y ) → Pre ULCβ (X), ULCβ (Y ) .
     Remark 2.86        (about Substitution).      The substitution in Ex. 2.85 is compatible
with the order on terms in the following sense:

(1)   M ≤ N implies M [∗ := A] ≤ N [∗ := A]                   and

(2)   A ≤ B implies M [∗ := A] ≤ M [∗ := B].
The rst implication is a general fact for any relative monad                  P     on∆: it is a special
case of     σX,Y (f )   being a morphism in the category             Pre   for any   f ∈ Pre(∆V, P W ).
The second monotony property, however, is                  false    in general. As an example, con-




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                Initiality for Typed Syntax and Semantics                        ·    47




sider the monad given by

                             F (V ) ::=        Var : V → F (V )
                                          | ⊥ : F (V )
                                          | (⇒) : F (V ) × F (V ) → F (V )
equipped with a preorder which is contravariant in the rst argument of the arrow
constructor      ⇒.       Substituting in this position, the rst argument of                            (⇒),    does in
fact   reverse   the order on terms, i.e. we obtain (using                             ⇒   inxed)

                 A<B          implies      (∗ ⇒ M )[∗ := B] < (∗ ⇒ M )[∗ := A] .
A dierent denition of monad which would enforce the second implication to hold
 and hence not include the example                   F       can be given easily by considering                    Pre
as a 2category enriched over itself: given morphisms                                  f, g ∈ Pre(X, Y )   we say that
there is precisely one 2cell

                           f ⇒g     i    f ≤g        i                 ∀x : X, f (x) ≤ g(x) .
A monad      P   would then have to be equipped with a substitution action that is
given, for any two sets         V   and   W,    by   a functor                (of preorders)

                              σV,W : Pre(∆V, P W ) → Pre(P V, P W ) .
Denition 2.110 explains one of the consequences of our monadic substitution lack-
ing higherorder monotonicity.

     We generalize the denition of colax monad morphisms to relative monads:

                                                                                                                      F
     Denition 2.87 (Colax Morphism of Relative Monads,                                    Code 6.18).     Let   P :C→
                      0
                  F
D and Q : C 0 → D0 be two relative monads. A colax morphism of relative monads
from P to Q is given by a quadruple (G, G0 , N, τ ) consisting of a functor G : C → C 0
                0         0                                              0        0
and a functor G : D → D as well as a natural transformation N : F G → G F as
in


                                                C
                                                            F              /D

                                                      N         ;C
                                            G                                 G0

                                                                            
                                               C0                         / D0 .
                                                       F0

and a natural transformation              τ : G0 ◦ P → Q ◦ G                       as in


                                                C
                                                            P              /D

                                            G          {            τ        G0

                                                                            
                                               C0                         / D0 ,
                                                            Q




                                                            Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
48        ·           B. Ahrens




such that the following diagrams commute for all suitable morphisms                                                                  f:
                      G0 σ P (f )                                                                                           G0 ηcP
     G0 P c                              / G0 P d                  F 0 Gc
                                                                                            Nc            / G0 F c                             / G0 P c


     τc                                           τd                                                                                                    τc
                                                                                                            Q
                                                                                                           ηGc

                                                                                                                                         (    
     QGc                                 / QGd                                                                                                 QGc.
                  Q         0
              σ       (τd ◦G f ◦N c)
     Remark 2.88.               Naturality of                 τ    in the preceding denition is actually a conse-
quence of the commutative diagrams of Def. 2.87.

     Remark 2.89.               In Sect. 5 we are going to use the following instance of the pre-
                                                                                                                                                    0
ceding denition: the categories                               C    and      C0           are instantiated by              SetT   and     SetT          , re-
spectively, for sets                T   and       T 0.
                                           G is the retyping functor (cf. Rem. 2.23)
                                                           The functor
                                                  0
associated to some translation of types g : T → T . Similarly, the categories D and
  0                       T         T0
D are instantiated by Pre and Pre , and the functor F by
                                                         F := ∆T : SetT → PreT ,
and similar for            F 0:

                                                            SetT
                                                                            ∆T              / PreT

                                                                            Id   ;C
                                                               ~
                                                               g                               ~
                                                                                               g

                                                                                              
                                                            SetT
                                                                  0
                                                                                            / PreT 0 .
                                                                                      0
                                                                            ∆T

Given a monad               P   on      F : C → D, the notion of module over P                                         generalizes the notion
of monadic substitution:
                                                                                                                                                F
     Denition 2.90             (Module over a Relative Monad, Code 6.19).                                       P : C → D be
                                                                                                                            Let
a relative monad and let                      E     be a category. A                       module M over P with codomain E is
given by

a map        M :C→E                    on the objects of the categories involved and

for all      objects c, d              of   C,   a map

                                                    ςc,d : D(F c, P d) → E(M c, M d)
such that the following diagrams commute for all suitable morphisms                                                                  f    and       g:
                                                  ς (f )
                                    Mc                       / Md                           Mc
                                                                                                             ς (ηc )

                                                                    ς (g)
                                    ς (σ (g)◦f )
                                                              !                                     id
                                                                                                                 * M c.
                                                               Me

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                            Initiality for Typed Syntax and Semantics            ·    49




A functoriality (rmlift) for such a module               M    is then dened similarly to that for
monads: for any morphism           f :c→d      in   C   we set

                              M (f ) := rmliftM (f ) := ς(η ◦ F f ) .
The following examples of modules are instances of constructions explained in the
next section:

  Example 2.91 (Ex. 2.85 cont.). The map ULCβ : V 7→ ULCβ (V ) yields a module
over the relative monadULCβ , the tautological module ULCβ .
  Example 2.92.                V 0 := V + 1. The map ULC0β : V 7→ ULCβ (V 0 )
                     Recall that
inherits the structure of an ULCβ module from the tautological module ULCβ (cf.
                       0
Ex. 2.91). We call ULCβ the derived module of the module ULCβ ; cf. also Sect. 2.4.2.

  Example 2.93. The map V 7→ ULCβ (V ) × ULCβ (V )                          inherits a structure of an
ULCβ module from the tautological module ULCβ .
  A   module morphism         is a family of morphisms that is compatible with module
substitution in the source and target modules:

  Denition 2.94     (Morphism of Relative Modules, Code 6.20).                   Let M and N be
                                         F
two relative modules over         P: C → D       with codomain            E.   morphism of relative
                                                                               A
P modules    from   M   to   N   is given by a collection of            morphisms ρc ∈ E(M c, N c)
such that for all morphisms         f ∈ D(F c, P d)        the following diagram commutes:

                                                ς M (f )
                                        Mc                   / Md

                                       ρc                        ρd

                                                               
                                        Nc                   / N d.
                                                    N
                                                ς (f )

The modules over   P with codomain E and morphisms between them form a category
called   RMod(P, E) (in the digital library: RMOD P E). Composition and identity
morphisms of modules are dened by pointwise composition and identity, similarly
to the category of monads.

  Example 2.95 (Ex. 2.91, 2.92,         Ex. 2.93 cont.).              Abstraction and application are
morphisms of ULCβ modules:
                                  Abs : ULC0β → ULCβ ,
                                App : ULCβ × ULCβ → ULCβ .
  2.4.2    Constructions on Relative Monads and Modules.                       The following construc-
tions are analogous to those of Sect. 2.2.2.

 Denition 2.96 (Tautological Module).                   Every monad           P   on   F :C→D   yields a
module(P, σ P )  also denoted by P                    over itself, i.e. an object in the category
RMod(P, D).
  Denition 2.97 (Constant and Terminal Module). Let P be a monad on F :
C → D. For any object e ∈ E the constant map Te : C → E , c →
                                                            7 e for all c ∈ C , is
                                                    Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
50       ·    B. Ahrens




equipped with the structure of a              P module      by setting      ςc,d (f ) = ide .   In particular,
 E has a terminal
if                      object   1E ,   then the constant module              T1E : c 7→ 1E      is terminal in
RMod(P, E).
  Denition 2.98 (Postcomposition with a functor). Let P be a monad on F :
C → D, and let M be a P module with codomain E . Let G : E → X be a functor.
Then the object map G ◦ M : C → X dened by c 7→ G(M (c)) is equipped with a
P module structure by setting, for c, d ∈ C and f ∈ D(F c, P d),
                                        ς G◦M (f ) := G(ς M (f )) .
For    M := P and G a constant functor mapping to an object x ∈ X and its identity
morphism    idx , we obtain the constant module (Tx , id) as in the preceding denition.
   Denition 2.99 (Pullback Module). Suppose given                           two relative monads        P   and
Q and a morphism τ : P → Q as in Def. 2.87. Let N                            a   Q-module    with codomain
E . We dene a P -module h∗ M to E with object map
                                                   c 7→ M (Gc)
by dening the substitution map, for                 f : F c → P d,     as
                                  ∗
                               ςh     M
                                          (f ) := ς M (hd ◦ G0 f ◦ Nc ) .
The module thus dened is called the                  pullback module of N along h.              The pullback
extends to module morphisms and is functorial.

     Denition 2.100    (Induced Module Morphism).                      With the same notation as be-
fore, the monad morphism            h   induces a morphism of         P modules h : G0 P → h∗ Q.
Note that the domain module is the module                      obtained by postcomposing P with
G0 ,   whereas for (plain) monads the module was just the tautological module of the
domain monad.

     Denition 2.101 (Product). Suppose the category E is equipped with a product.
Let   M and N be P modules with codomain E . Then the map
                              M × N : C → E,                c 7→ M c × N c
is canonically equipped with a substitution and thus constitutes a module called
the    product of M and N .      This construction extends to a product on                       RMod(P, E).
     2.4.3  Derivation & Fibre. We are particularly interested in monads on the func-
tor    ∆T : SetT → PreT for some set T , and modules over such monads. The con-
structions on modules over monads of Sect. 2.2.3, derivation (cf.  2.2.3.1) and bre
modules (cf.  2.2.3.2), carry over to modules over monads on                         ∆T .
     Denition 2.102.     Given a monad             P over ∆T and a P module M with codomain
E,   we dene the derived module of                M with respect to u ∈ T by setting
                                          M u (V ) := M (V ∗u ) .
The module substitution is dened, for                  f ∈ PreT (∆T V, P W ),       by

                                              Mu           M
                                          ς        (f ) := ς (u f ) .


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                           Initiality for Typed Syntax and Semantics          ·     51




Here the shifted map

                                     ∈ PreT ∆T (V ∗u ), P (W ∗u )
                                                                       
                                uf

is the adjunct under the adjunction of Rem. 2.21 of the coproduct map

                  ϕ(u f ) := [P (inl) ◦ f, η(inr(∗))] : V ∗u → U P (W ∗u ) ,
where    [inl, inr] = id : W ∗u → W ∗u .        Derivation is an endofunctor on the category
of   P modules with codomain E .
     Notation 2.103.    In case the set     T   of types is   T = {∗} the singleton set of types,
i.e. when talking about untyped syntax, we denote by                 M 0 the derived module of
M . Given a natural number n,           we denote by     Mn    the module obtained by deriving
n times the module M .
     Analogously to Sect. 2.2.3, we derive more generally with respect to a natural
transformation    τ : 1 → T Un       as in Def. 2.57:

 Denition 2.104 (Derived Module). Let τ : 1 → T Un be a natural trans-
                                                              T
formation.   Let T be a set and P be a relative monad on ∆n . Given any P 
module M , we call derivation of M with respect to τ the module with object map
                      
M τ (V ) := M V τ (V ) .
   Denition 2.105. Let P be a relative monad over F , and M a P module with
codomain   E T for some category E . The bre module [M ]t of M with respect to
t ∈ T has object map
                                      c 7→ M (c)(t) = M (c)t
and substitution map

                                      ς [M ]t (f ) := ς M (f ) t .
                                                              

This denition generalizes to bres with respect to a natural transformation as in
Def. 2.104.
     The pullback operation commutes with products, derivations and bres :

  Lemma 2.106: Let C and D be categories and E be a category with products.
Let P : C → D and Q : C → D be monads over F : C → D and F 0 : C 0 → D0 , resp.,
and ρ : P → Q a monad morphism. Let M and N be P modules with codomain E .
The pullback functor is cartesian:
                                       ∼ ρ∗ M × ρ∗ N .
                           ρ∗ (M × N ) =
     Lemma 2.107:  Consider the setting as in the preceding lemma, with F = ∆T ,
and t ∈ T . Then we have
                              ρ∗ (M t ) ∼
                                        = (ρ∗ M )t .
     Lemma 2.108:       Suppose N is a Qmodule with codomain E T , and t ∈ T . Then
                                   ρ∗ [M ]t ∼
                                            = [ρ∗ M ]t .
     Denition 2.109.    Recall that the category           wPre     is the category of preordered
sets and settheoretic maps (not necessarily monotone) between them (Def. 2.9).
Given a relative monad      P   on some functor         F   and a    P module M    with codomain

                                                   Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
52      ·     B. Ahrens




Pre, we can consider M           as a   P module with codomain wPre.            We denote this module
by M̂ . In other words,          we have a functor

                                 ˆ
                                 _   : RMod(P, Pre) → RMod(P, wPre)
obtained by postcomposition with the forgetful functor from                       Pre   to   wPre.
     Denition 2.110 (Substitution of one Variable). Let P                   be a monad over         ∆.   For
any set  X , we dene a binary substitution operation
            subst(X) : P (X ∗ ) × P (X) → P (X),
                                          (y, z) 7→ y[∗ := z] := σ (default(ηX , z)) (y) ,
where  default is a coproduct map; for              f :A→B        and   z ∈ B,
                        default(f, z) := [f, x 7→ z] : A + {∗} → B .
This denes a morphism of               P modules   with codomain        wPre,
                                                P     0
                                          subst : P̂ × P̂ → P̂ .
The reason why we have to consider the category                   wPre    with   all settheoretic    maps
instead of just monotone maps is that                 substP   is not necessarily monotone in its
second argument, cf. Rem. 2.86.

     The untyped substitution of Def. 2.110 actually is a special case of the following
typed substitution:

     Denition 2.111 (Substitution of one Variable, typed). Let T be a                         (nonempty)
set and let   P be a monad over ∆T . For any s, t ∈ T and X ∈ SetT                             we dene a
binary substitution operation

         substs,t (X) : P (X ∗s )t × P (X)s → P (X)t ,
                                            (y, z) 7→ y[∗ := z] := σ (default(ηX , z)) (y) .
                             2
For any pair    (s, t) ∈ T       , we thus obtain a morphism of           P modules
                                     substP        s
                                          s,t : [P̂ ]t × [P̂ ]s → [P̂ ]t .

3.    SIMPLE TYPE SYSTEMS
In this chapter we present two generalizations to simple type systems of Hirschowitz
and Maggesi's initiality theorem for untyped syntax [HM07a]:

in Sect. 3.2 we review Zsidó's theorem [Zsi10, Chapt. 6].

In Sect. 3.3 we prove a variant of Zsidó's theorem which accounts for translations
     between languages over          dierent   sets of object types.

We explain the dierence between the two abovementioned theorems in more detail:
     in Zsidó's theorem, the underlying set of types of a signature  and thus of the
term language the signature species  is given as a xed parameter. In particular,
all the models  representations  of the signature have the same underlying set
of types.    Furthermore, this set does not necessarily have inductive structure, as
opposed to the sets of types we characterize via initiality in Sect. 3.1  the content
of Sect. 3.2 is independent of that of Sect. 3.1.

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                          Initiality for Typed Syntax and Semantics        ·      53




  In our variant of Zsidó's theorem we prove in Sect. 3.3, a language is specied by
a pair (S, Σ) of signatures, a signature S for types as presented in Sect. 3.1, and a
signature Σ for terms over the signature S . A representation of such a signature is
given by a pair of a representation of S and a representation of Σ. In particular,
we consider models of (S, Σ) whose underlying set of types is dierent from the
set freely generated by the signature S . The initiality result of Sect. 3.3 thus
characterizes both the types and terms freely generated by a signature as initial
object in a category of representations.
  As running examples, we consider the simplytyped lambda calculus and Plotkin's
PCF    [Plo77]. In Sect. 3.4 we present a logic translation from classical to intuition-
istic propositional logic as an instance of our theorem of Sect. 3.3. Before focusing
on    term signatures, however, we review, in Sect. 3.1, algebraic         signatures as treated
by Birkho [Bir35]. Algebraic signatures are used in Sect. 3.3 for the specication
of the set of types of a language.


3.1     Signatures for Types
We present     algebraic signatures,      which later are used to specify the          object types
of the languages we consider.           Algebraic signatures and their models were rst
considered by Birkho [Bir35].

  Denition 3.1      (Algebraic Signature).       An   algebraic signature S      is a family of
natural numbers, i.e. a set     JS   and a map (carrying the same name as the signature)
S : JS → N. For j ∈ JS and n ∈ N, we also write j : n instead                     of   j 7→ n.   An
element of J resp. its image under S is called an arity of S .

  Example 3.2       (Algebraic Signature of Ex. 1.3).          The algebraic signature of the
types of the simplytyped lambda calculus is given by

                                STLC := {∗ : 0 ,       (;) : 2} .
To any algebraic signature we associate a category of   representations. We call
representation of S any set U equipped with operations according to the signature
S . A morphism of representations is a map between the underlying sets that is
compatible with the operations on either side in a suitable sense. Representations
and their morphisms form a category. We give the formal denitions:

  Denition 3.3 (Representation of an Algebraic Signature S , S Algebra).                  A    rep-
resentation R of an algebraic signature S  also known as S algebra                      is given
by

a set    X   and

for each     j ∈ JS ,   an operation   j R : X S(j) → X .
In the following, given a representation        R,   we write   R   also for its underlying set.

  Example 3.4.       The language       PCF [Plo77, HO00] (see also Sect. A.1) is a simply
typed lambda calculus with a xed point operator and arithmetic constants. Let
J := {ι, o, (⇒)}.    The signature of the types of       PCF    is given by the arities

                            SPCF := {ι : 0 ,     o:0 ,       (⇒) : 2} .


                                                Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
54         ·       B. Ahrens




A representation              T    of   SPCF   is given by a set           T    and three operations,

                                    ιT : T ,        oT : T ,           (⇒)T : T × T → T .
A morphism of representations is given by a map between the underlying sets that
is compatible with the representation structure:

  Denition 3.5 (Morphisms of Representations). Given two representations T
and U of the algebraic signature S , a morphism from T to U is a map f : T → U
such that, for any arity n = S(j) of S , we have

                                              f ◦ j T = j U ◦ (f × . . . × f ) .
                                                               |   {z      }
                                                                           n   times


  Example 3.6 (Ex. 3.4 continued). Given two representations T and U of SPCF , a
morphism from      T to U is a map f : T → U between the underlying sets such that,
for any s, t ∈ T ,

                                                      f (ιT ) = ιU ,
                                                     f (oT ) = oU              and

                                               f (s ⇒ t) = f (s) ⇒U f (t) .
                                                           T


Representations of an algebraic signature                              S   and their morphisms form a category.

   Lemma 3.7: Let (J, S) (or S for short) be an algebraic signature. The category
of representations of S has an initial object Ŝ .
Proof.         We cut the proof into small steps:

In a typetheoretic setting the set  also called                                     Ŝ    which underlies the initial
     representation           Ŝ    is dened as an inductive set with a family of constructors
     indexed by        JS :
                                          Ŝ ::=               C : ∀j ∈ J, Ŝ S(j) → Ŝ .
     That is, for each arity              j ∈ J,      we have a constructor                  Cj : Ŝ S(j) → Ŝ .
For each arity            j ∈ J,        we must specify an operation                       j Ŝ : Ŝ S(j) → Ŝ .   We set

                                                    j Ŝ := Cj : Ŝ S(j) → Ŝ ,

     that is, the representation                    j Ŝ   of an arity         n = S(j)            is given precisely by its
     corresponding constructor.

Given any representation                       R    of        S,   we specify a map           iR : Ŝ → R          between the
     underlying sets by structural recursion:

                                                               iR Cj (a) := j R (iR )S(j) (a) ,
                                                                                            
                                   iR : Ŝ → R ,
     for   a ∈ Ŝ S(j) .   That is, the image of a constructor function                                 Cj   maps recursively
     on the image of the corresponding representation                                   jR    of   R.
We must prove that                      iR   is a morphism of representations, that is, that for any
     j∈J        with   S(j) = n,

                                                     iR ◦ j Ŝ = j R ◦ (iR )n .

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                 Initiality for Typed Syntax and Semantics                       ·   55




     Replacing        j Ŝ   by its denition yields that this equation is precisely the specica-
     tion of   iR ,   see above.

It is the diagram of Def. 3.5 which ensures uniqueness of iR ; since any morphism
     of representations           i0 : Ŝ → R must make        it commute, one can show by structural
                               0
     induction that            i = iR . More precisely:
                                                                                             i0 (ak )=iR (ak )
         i0 (Cj (a)) = i0 (Cj (a1 , . . . , aS(j) )) = j R (i0 (a1 ), . . . , i0 (aS(j) ))          =
                                                           R
                                                      = j (iR (a1 ), . . . , iR (aS(j) )) = iR (Cj (a)) .


     Example 3.8             (Ex. 3.4 continued).     The set       TPCF   underlying the initial represen-
tation of the algebraic signature              SPCF    is given by

                                    TPCF ::=      ι | o | TPCF ⇒ TPCF .
For any other representation              R of SPCF     the initial morphism iR              : TPCF → R is given
by the clauses



                                             iR (ι) = ιR
                                            iR (o) = oR
                                        iR (s ⇒ t) = iR (s) ⇒R iR (t) .
3.2     Zsidó's Theorem Reviewed
We present Zsidó's initiality theorem [Zsi10, Chapt. 6] (cf. Thm. 3.28) for simply
typed abstract syntax.                Its formalization in the proof assistant                 Coq      is explained
in Sect. 7.       Throughout this section the number given in the name of each def-
inition points to the implementation of this denition in                           Coq.       For instance, the
implementation of Simple Monad Morphisms (Def. 3.12) is given in Code 6.13.
     Our presentation follows the pattern outlined at the beginning of Sect. 1.2: in
Sect. 3.2.1 we present classic signatures in two dierent ways.                                   Afterwards, in
Sect. 3.2.2, we give the denition of representations of such signatures.                                    Finally,
in Sect. 3.2.3, we state the main theorem, proved by Zsidó [Zsi10].

     3.2.1     Signatures for Terms.           In  3.2.1.1 we give a purely syntactical denition
of   classic    arities.        Afterwards, in  3.2.1.2 we give a denition of arities as pairs
of functors on suitable categories, and identify a subclass of arities which are in
onetoone correspondence with classic arities. We thus call arities of this subclass
classic      as well. In the following we x a set              T   of object types.

     3.2.1.1       Arities, syntactically. Syntactically, a classic arity consists of an element
of t0 ∈ T which species the output type of a constructor, as well as a list of pairs
([ti,1 , . . . , ti,mi ], ti ), where ti,k , ti ∈ T . Each such pair represents an argument of the
corresponding constructor: the element ti denotes the object type of the argument,
whereas the list [ti,1 , . . . , ti,mi ] species the types of the variables that are bound
by the constructor in this argument.

     Denition 3.9 (Classic T Arity, T Signature). A classic arity is of                              the form
                                                                                      
                 ([t1,1 , . . . , t1,m1 ], t1 ), . . . , ([tn,1 , . . . , tn,mn ], tn ) → t0 ,
                                                         Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
56       ·      B. Ahrens




where ti,k and ti are elements of         T.    We use an arrow to separate the data specifying
input data and output data, respectively. A                signature   is a family of arities. For a
formalized denition, see the            Coq   code snippets Code 7.1 and Code 7.2.

     Example 3.10     (Signature of       TLC).     The signature of the simplytyped lambda
calculus (cf. Ex. 1.3) is given by

        {abss,t : ([s], t) → (s ; t) ,            apps,t : ([], s ; t), ([], s) → t}s,t∈TTLC .
                                                                            

See the code snippet Code 7.3 for a              Coq   implementation of this example.

     3.2.1.2    Arities, semantically.         In this section we give a denition of arities as
pairs of functors between suitable categories. The source category (cf. Def. 3.13) is
a category of monads and morphisms of monads, whereas the target category (cf.
Def. 3.15) mixes modules over dierent such monads.
     At rst, in Rem. 3.11, we present an alternative characterization of algebraic
arities. This alternative point of view is then adapted to allow for the specication
of arities for terms.

     Remark 3.11      (Algebraic Arities viewed dierently).             An algebraic arity  j : n
as presented in Sect. 3.1 associates, to any set              X,   the set   dom(j, X) := X n , the
domain set. A representation R of this arity j in a set X then is given by a map
j R : X n → X . More formally, the domain set is given via a functor dom(j) : Set →
Set which associates to any set X the set X n . Similarly, we might also speak of
a codomain functor for any arity, which  for algebraic arities  is given by the
identity functor. A representation R of j in a set X then is given by a morphism

                                 j R : dom(j)(X) → cod(j)(X) .
We take the perspective of Rem. 3.11 in order to dene arities and signatures for
terms :            T of object types, an arity α for terms typed over T is a pair of
             given a set
functors (dom(α), cod(α)) associating two P modules dom(α)(P ) and cod(α)(P ),
to any suitable monad P . A suitable monad here is a monad P on the category
SetT . A representation R of α in a such a monad P is a module morphism
                                αR : dom(α)(P ) → cod(α)(P ) .
We consider monads as in Def. 2.33 (also: Def. 2.65) over a category of the form
SetT    for some xed set      T.    Throughout this section, morphisms between two such
monads over the same category are given by colax monad morphisms                           over the
identity functor,     i.e. those morphisms of Def. 2.38 (alt. Def. 2.69) with            F = IdSetT .
For convenience, and as a reference for the implementation in                    Coq,   we explicitly
state the denition of these simple monad morphisms, using the denition through
Kleisli operation (cf. Def. 2.69) of monads and morphisms:

     Denition 3.12        (Simple Monad Morphism, Code 6.13).   Let P and Q be two
monads over a category          C.  simple morphism of monads τ from P to Q is given
                                     A
by a collection of         morphisms τc ∈ C(P c, Qc) such that the following diagrams




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                          Initiality for Typed Syntax and Semantics               ·     57




commute for all suitable morphisms          f:
                             σ P (f )                                  ηcP
                       Pc                / Pd                   c            / Pc

                      τc                    τd                                  τc
                                                                     ηcQ
                                                                            
                       Qc                / Qd,                               Qc.
                             Q
                            σ (τd ◦f )

  Denition 3.13            Mon(C) of Monads on C ). Given a category C , we
                    (Category
dene the category Mon(C) to be the category whose objects are monads over C . A
morphism from P to Q in this category is a monad morphism as in Def. 3.12. We
denote by IC : Mon(C) → Mndcolax the inclusion functor.

  We dene a category in which modules over dierent monads  but with the
same codomain category  are mixed together. This category can be dened as a
particular   colax comma category.        However, we also give an explicit description of
the objects and morphisms of this category.

  Denition 3.14 (Colax Comma Category). Let C be a 2category, and c ∈ C be
an object ofC . Let A be a category and let F : A → C be a functor. An object of
the colax comma category (F ↓ c) is given by a pair (a, f : F a → c) of an object
a ∈ A and a morphism f : a → c. A morphism to another such (b, g : F b → c) is
given by a pair (h : a → b, α) as in the diagram


                                                        f

                                                                    &
                                 Fa                       α        :c .
                                          Fh
                                                       - Fb    g

While the above denition is not the most general denition possible for a colax
comma category, it is sucient for our needs:

   Denition 3.15 (Large Category LMod(C, D) of Modules). Given two categories
C and D, we dene the category LMod(C, D) to be the colax comma category
(IC ↓ IdD ). An object of this category is a monad P over C together with a P 
module with codomain D (cf. Def. 2.43). A morphism (f, h) to another such (Q, N )
is given by a morphism f : P → Q of monads over the identity functor  i.e., a
                                                              ∗
morphism in Mon(C)  and a morphism of modules h : M → f N = N ◦ f :



                                                 M
                                                                &
                                  P                    h      8 IdD .
                                                 N ◦f

  Denition 3.16 (Tautological Module).                     To any monad     R ∈ Mon(C) we associate
the tautological moduleΘ(R) of R,
                            Θ(R) := (R, R) ∈ LMod(C, C) .
This construction extends to a functor            Θ : Mon(C) → LMod(C, C).
                                                       Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
58         ·       B. Ahrens




     A halfarity associates a                 P module          towards      Set   to any monad        P   over   SetT :
     Denition 3.17           (HalfArity).            A     halfarity over T           is a functor

                                                             T                       T
                                       a : Mon(Set ) → LMod(Set , Set)
from the category of monads over                            SetT   to the large category of modules over such
monads with codomain                   Set,      such that

                                                   π1 ◦ a = idMon(SetT ) .                                               (3.1)

This last condition given in Disp. (3.1) ensures that each monad maps to a mod-
uleover itself. For              a monad          R ∈ Mon(SetT ), we thus sometimes                          omit the rst
component R of the               image         a(R) and consider a(R) ∈ Mod(R, Set).
     Denition 3.18 (Arity,                  Signature).           A   T arity s        is a pair   (dom(s), cod(s))         of
halfarities over T,
                             dom(s), cod(s) : Mon(SetT ) → LMod(SetT , Set) ,
written        dom(s) → cod(s).              A    T signature         is a family of      T arities.
     We give some important examples of halfarities over the set                                       T.   Note that, by
the convention of Def. 3.17, we omit the rst component of objects of the large
category of modules              LMod(SetT , Set).
     Denition 3.19.             Let   T     be a nonempty set, and let                   t∈T   be an element of         T.
                                           T                           T
The map    [Θ]t : Mon(Set ) → LMod(Set , Set) with object map R 7→ (R, [R]t ) is
                      bre with respect to t  over T .
     a halfarity  the
                                      t          T                    T       T
If M is a halfarity over T , so is M : Mon(Set ) → LMod(Set , Set), M (R) :=
       t
 M (R) (cf. Def. 2.55). By iterating, given t1 , . . . , tn ∈ T , the functor
                                       M (t1 ,...,tn ) : R 7→ (. . . (M (R)t1 ) . . .)tn
     is a halfarity.

If   M and N are half-arities over T ,                          then so is the product         M × N : Mon(SetT ) →
     LMod(SetT , Set):
                                             M × N : R 7→ M (R) × N (R) .
The map           R 7→ ∗, where ∗ : V 7→ 1Set                     is the terminal object in            Mod(R, Set),         is a
     halfarity over    T.
     An    arity   is a pair of halfarities. We are only interested in                          classic     arities, whose
domain and codomain functors are of a specic form:

   Denition 3.20 (Classic T Arity, T Signature (II)).                                   We call   classic T arity        any
T arity s of the form
                                         t       ...t1,m1                  t    ...tn,mn
                              s = [Θ]t11,1                  × . . . × [Θ]tn,1
                                                                          n
                                                                                            → [Θ]t0                      (3.2)

     for   ti,j , ti ∈ T .   A   classic T signature              is a collection of such classic arities.

     To an operator that binds                   mk    variables of types          tk,1 , . . . , tk,mk in its k th argu-
ment of type         tk ,    and which yields a term of type                    t0 , we associate the arity given in
Disp. (3.2).

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                            Initiality for Typed Syntax and Semantics          ·     59




    Remark 3.21.       The classic T arities and T signatures of Def. 3.20 and of Def. 3.9
are in bijection, respectively. We can thus specify       T signatures by simply giving a
term of the simple data        type dened in Def. 3.9. In the Coq formalization, arities
and signatures are dened via such data types, cf. Code 7.1 and Code 7.2.

    Remark 3.22.       In Def. 3.20 we can have          n = 0,   yielding an arity for constants
of, say, object type     t0 ∈ T ,
                                           s = ∗ → [Θ]t0 .
Such an arity then is given by an empty list of arguments according to Def. 3.9.
An example of a constant arity is given in Ex. 3.48.

    As an example we discuss the classic signature of the simply typed lambda cal-
culus:

    Example 3.23 (Signature of TLC, Code 7.3).              Consider the example of the simply
typed lambda calculus (cf. Exs. 1.3, 2.37). Its signature is given syntactically in
Ex. 3.10. Equivalently, it is given by the signature

                                   ΣTLC = {abss,t , apps,t }s,t∈TTLC
with

                                abss,t := [Θ]st → [Θ]s;t            and

                                apps,t := [Θ]s;t × [Θ]s → [Θ]t .
    Remark 3.24.       Note that in Ex. 3.23 we do not need to explicitly specify an arity
for the Var term      constructor in order to obtain the simplytyped lambda calculus
as presented in Ex. 1.3. Indeed, by building models from monads (cf. Def. 3.25)
every model is by denition equipped with a corresponding operation  the unit
of the underlying monad.

    3.2.2   Representations. A representation of an arity s in a monad P is given                    by
a morphism of    P modules whose domain and codomain are determined by s:
    Denition 3.25 (Representation          of a   T Signature,   Code 7.4).      A representation
R   of a T signature Σ is given by

a monad        P   on the category    SetT   and

for any arity       s ∈ Σ,   a morphism of modules in         LMod(SetT , Set),
                                    sR : dom(s, P ) → cod(s, P ) ,
    such that   π1 (sR ) = idP .
Given a representation        R,   we denote by     R   also the underlying monad.

    Morphisms of representations are monad morphisms that are compatible with
the representation module morphisms:

    Denition 3.26 (Morphism of Representations). Let P and Q be representations
of a  T signature Σ. A morphism of representations f : P → Q is a morphism f



                                                    Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
60      ·           B. Ahrens




between the underlying monads such that the following diagram commutes for any
arity   s    of   Σ:

                                 dom(s, P )
                                                           sP              / cod(s, P )                      (3.3)



                                  dom(s,f )                                   cod(s,f )


                                                                             
                                 dom(s, Q)                                 / cod(s, Q).
                                                           Q
                                                           s

The preceding diagram can be seen as a diagram in two dierent categories, either
in the category            LMod(SetT , Set),       or in the category       Mod(P, Set)     of   P modules.
     Denition 3.27          (Category of Representations).                  Morphisms of representations
can be composed: the composition of the underlying monad morphisms again gives
a morphism of representations.                     Similarly the identity morphism of monads is a
morphism of representations.                   Two morphisms of representations are said to be
equal if their underlying morphisms of monads are equal.                                  Representations and
their morphisms of a signature                 Σ   form a category         Rep(Σ).
     3.2.3        Initiality.   The main theorem states that any              T signature admits an initial
representation:

  Theorem 3.28: Let Σ be a classic T signature. Then the category Rep(Σ) of
representations of Σ has an initial object.
     Remark 3.29. The              monad underlying the initial representation associates, to
any context  V ∈ SetT ,            the set of terms of the syntax of             Σ   with free variables in    V.
The module morphisms of the initial representation are given by the constructors
of this syntax.

     A settheoretic construction of the syntax as well as a proof of the theorem is
given in Zsidó's PhD thesis [Zsi10]. In Sect. 7.2 we explain the implementation of
the main theorem in a typetheoretic setting in the proof assistant                              Coq.

3.3     Extending Zsidó's Theorem to Varying Types
Zsidó's initiality result of Thm. 3.28 does not account for varying object sorts.
Indeed, given a signature               Σ     over a set       T   of object sorts, any representation of
Σ    has the same set of sorts                T,   i.e. its underlying monad is a monad on the
category          SetT .   In this section we give a new denition of signatures and their
representations, and prove that the resulting category of representations has an
initial object. The iteration operator obtained from this initiality result accounts
for translations between languages over dierent sets of sorts. We dene a                                   typed
signature         to be a pair    (S, Σ)    consisting of an algebraic signature            S    for sorts, and a
signature         Σ    for terms typed over the sorts specied by               S.   A representation of such
a typed signature consists of a representation of the sort signature                             S   in some set   T
and a representation of            Σ   in a monad over the category              SetT .   Translations of sorts
are given by morphisms of representations of                         S,   that is, by maps of sets that are
compatible with the representations of sorts constructors in the source and target.

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                      Initiality for Typed Syntax and Semantics                  ·       61




Compared to Zsidó, we thus restrict ourselves to sets of sorts that have                                    inductive
structure,      whereas for Zsidó, the set of sorts is given by an arbitrary parameter.

    3.3.1     Signatures for Types & Terms.                      Before starting with the formal deni-
tions, we informally consider the example of the simplytyped lambda calculus; its
signature for terms was given in the preceding section (cf. Ex. 3.23) as:

 {abss,t := ([s], t) → (s ; t) ,                       apps,t := ([], s ; t), ([], s) → t}s,t∈TTLC .
                                                                                  
                                                                                                                     (3.4)

The parameters            s   and      t   range over the set    TTLC   of types, the initial representation
                                                                                                      2
of the signature for types from Ex. 3.2. In particular, we have                                  2 × TTLC   arities in
this signature.
    Our goal is to consider representations of the simplytyped lambda calculus in
monads over categories of the form                         any set T  provided that T is
                                                          SetT    for
equipped with a representation of the signature              STLC . Clearly, the above signa-
ture of Disp. (3.4),           with its strong dependence on the set TTLC is not wellsuited to
express this. Instead of the above signature, we would like to write

         {abs := ([1], 2) → (1 ; 2) ,                        app := ([], 1 ; 2), ([], 1) → 2} .
                                                                                     
                                                                                                                     (3.5)

What is the intended meaning of such a signature?                              For any representation                T   of
STLC ,   the variables          1   and      2   range over elements of     T.    In this way the number of
abstractions and applications depends on the representation                            T     of   STLC :   intuitively,
a representation of the above signature of Disp. (3.5) over a representationT of
TTLC has T 2 abstractions and T 2 applications  one for each pair of elements of
T . As an example, for the nal representation of STLC in the singleton set, one
obtains only one abstraction and one application morphism. We call arities, that
contain object type variables, arities                   of higher degree,       where the degree of such an
arity denotes the number of (distinct) type variables. For instance, the arities                                      abs
and   app     of Disp. (3.5) are of degree              2.
    3.3.1.1      Term Arities, syntactically.                 In Sect. 3.2, arities over a xed set of object
types    T   were dened purely syntactically, namely using pairs and lists, cf. Def. 3.9.
We give a similar syntactic characterization of arities over a xed algebraic signature
S   for types as in Def. 3.1.

   Denition 3.30 (Type of Degree n). For n ≥ 1, we call types of S of degree n the
elements of the set      S(n) of types associated to the signature S with free variables
in the set {1, . . . , n}. We set S(0) := Ŝ . Formally, the set S(n) may be obtained as
the initial representation of the signature S enriched by n nullary arities.

    Types of degree           n   are used to form classic arities of degree                n:
    Denition 3.31 (Classic Arity of Degree n). A classic arity for terms                                    over the
signature  S for types of degree n is of the form
                                                                                      
                 ([t1,1 , . . . , t1,m1 ], t1 ), . . . , ([tk,1 , . . . , tk,mk ], tk ) → t0 ,                       (3.6)

where    ti,j , ti ∈ S(n).             More formally, a classic arity of degree    n over S is a pair
consisting of an element t0                  ∈ S(n) and a list of pairs. where each pair itself consists
of a list    [ti,1 , . . . , ti,mi ]   of   elements of S(n) and an element ti of S(n).

    A classic arity of the form given in Disp. (3.6) denotes a constructor  or a
family of constructors, for                  n≥1       whose output type is         t0 ,   and whose        k   inputs

                                                              Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
62       ·       B. Ahrens




are terms of type               ti , respectively, in each of which variables           of type according to
the list     [ti,1 , . . . , ti,mi ] are bound by the constructor.
     Remark 3.32.        For an arity as given in Disp. (3.6) we also write

                          t     ,...,t1,m1                  tk,1 ,...,tk,mk
                       [Θn1,1                ]t1 × . . . × [Θn                ]tk → [Θn ]t0 .          (3.7)

Examples of (classic) arities are to be found in Ex. 3.47 and Sect. 3.4.

     Remark 3.33      (Implicit Degree).                  n ∈ N as in Def. 3.31 can
                                                     Any arity of degree
also be considered as an arity of degree                  n + 1.
                                                              S(ω) the set of types
                                                                   We denote by
associated to the type signature S with free variables in N. Then any arity of
degree n ∈ N can be considered as an arity built over S(ω). Conversely, any arity
built over S(ω) only contains a nite set of free variables in N, and can thus be
considered to be an arity of degree n for some n ∈ N. In particular, by suitable
renaming of free variables, there is a minimal degree for any arity built over S(ω).
We can thus omit the degree  e.g., the lower inner index n in Disp. (3.7) , and
specify any arity as an arity over S(ω), if we really want to consider this arity to
be of minimal degree. Otherwise we must specify the degree explicitly.

     3.3.1.2     Term Arities, semantically.              We now attach a meaning to the purely
syntactically dened arities of  3.3.1.1. More precisely, we dene arities as pairs
of functors over suitable categories. Afterwards we restrict ourselves to a specic
class of functors, yielding arities which are in onetoone correspondence to  and
thus can be compactly specied via  the syntactically dened classic arities of
                                                                classic arities.
 3.3.1.1. Accordingly, we call the restricted class of arities also
     Throughout this section, we x an algebraic signature S for types. An arity
α of degree n for terms over S is a pair of functors (dom(α), cod(α)) associating
two P modules dom(α, P ) and cod(α, P ), each of degree n, to any suitable monad
P . A suitable monad here is a monad P on some category SetT where the set T
is equipped with a representation of S . We call such a monad an S monad. A
representation R of α in an S monad P is a module morphism

                                      αR : dom(α, P ) → cod(α, P ) .
As we have seen in Ex. 1.3, constructors can in fact be                             families of constructors
indexed by type variables.               For such a constructor indexed               n times, we consider
modules        of degree n    (cf. Rem. 3.37).
     We dene a family of categories of monads which will play the role of the category
dened in Def. 3.13:

   Denition 3.34 (S Monad). Given an algebraic signature S , the 2category
S -Mnd of S monads is dened as the 2category whose objects are pairs (T, P )
                                                            T
of a representation T of S and a monad P : Set                 → SetT . A morphism from
(T, P ) to (T 0 , P 0 ) is a pair (g, f ) of a morphism of S representations g : T → T 0
                                             0
and a monad morphism f : P → P over the retyping functor ~                 g (cf. Rem. 2.23).
Transformations are the transformations of Mndcolax .
   Given n ∈ N, we write S -Mndn for the 2category whose objects are pairs (T, P )
                                                             T
of a representation T of S and a monad P over Setn . A morphism from (T, P ) to
(T 0 , P 0 ) is a pair (g, f ) of a morphism of S representations g : T → T 0 and a monad
                             0
morphism f : P → P over the retyping functor ~           g (n) (cf. Def. 2.28).
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                               Initiality for Typed Syntax and Semantics               ·    63




We call   IS,n : S -Mndn → Mndcolax             the functor which forgets the representation of
S.
     We dene a large category of modules in which modules over dierent                          S monads
are mixed together:

     Denition 3.35   (Large Category of Modules).Given a natural number n ∈ N,
an algebraic signature  S and a category D, we call LModn (S, D) the colax comma
category IS,n ↓ (D, Id). An object of this category is a pair (P, M ) of a monad
P ∈ S -Mndn and a P module with codomain D. A morphism to another such
(Q, N ) is a pair (f, h) of an S monad morphism f : P → Q in S -Mndn and a
                            ∗
transformation h : M → f N :

                                                      M
                                                                   &
                                      P                   h      8 IdD .
                                                     N ◦f

A halfarity over     S   of degree   n   is given by a functor from the category of monads
to the large category of modules:

     Denition 3.36 (HalfArity over S (of degree n)).                      Given an algebraic signature
S    and n ∈ N, we call halfarity over S of degree n a                   functor

                                α : S -Mnd → LModn (S, Set)
which is preinverse to the forgetful functor.

     Taking into account Rem. 3.37, this means that a halfarity of degree                         n associates
to anyS monad R  with representation of S                         in a set   T    a family of   Rmodules
indexed n times by T .

   Remark 3.37 (Module of Higher Degree corresponds to a Family of Modules).
Let C be a category, let T be a set and R be a monad on C T . Suppose n ∈ N, and
let D be a category. Then modules over Rn with codomain D correspond precisely
                                       n
to families of Rmodules indexed by T    with codomain D by (un)currying. More
                                               n
precisely, let M be an Rn module. Given t ∈ T , we dene an Rmodule Mt by

                                          Mt (c) := M (c, t) .
Module substitution for       Mt   is given, for           f ∈ C T (c, Rd),    by
                                               Mt               M
                                           ς        (f ) := ς (f )
where we use that we also have          f ∈ CnT ((c, t), (Rd, t)) according to Def. 2.26. Going
the other way round, given a          family (Mt )t∈T n , we dene the Rn module M by

                                          M (c, t) := Mt (c) .
                         T                                            T
Given a morphism f ∈ Cn ((c, t), (Rd, t))  recall that morphisms in Cn are only
between families with the same marker t , we also have f ∈ C (c, Rd) and dene
                                                              T

                                          ς M (f ) := ς Mt (f ) .
The remark extends to morphisms of modules; indeed, a morphism of modules
α : M → N on categories with pointed index sets corresponds to a family                                      of
        (αt : Mt → Nt )t∈T n between the associated families of modules.
morphisms

                                                           Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
64       ·     B. Ahrens




     As in Sect. 3.2, we restrict our attention to halfarities which correspond, in a
sense made precise below, to the syntactically dened arities of Def. 3.31. The basic
brick is the    tautological module of degree n:
   Denition 3.38. Given a category C and n ∈ N, any monad R on the category
C T induces a monad Rn on CnT with object map (V, t1 , . . . , tn ) 7→ (RV, t1 , . . . , tn ),
as is already indicated for functors in Def. 2.26.

     Denition 3.39 (Tautological Module of Degree n). Let n ∈ N be a                                       natural
number. To any    S monad R we associate the tautological module of Rn ,
                             Θn (R) := (Rn , Rn ) ∈ LModn (S, SetTn ) .
This construction extends to a functor                     Θn : S -Mnd → LModn (S, SetTn ).
     Let us consider the signature               STLC TLC. In the syntactically dened
                                                          of types of
arities (cf. Disp. (3.5)) we write terms like   1 ; 2. We now give meaning to such
a term: let T be any representation of STLC , that is, a set T together with a base
type ∗ ∈ T and a binary operation (;) : T × T → T . Intuitively, the term 1 ; 2
should associate, to an object (T, V, t1 , t2 ) with a T indexed family V of sets and
t1 , t2 ∈ T , the element t1 ; t2 ∈ T . More formally, such a term is interpreted by
a natural transformation (cf. Def. 3.41) over a specic category, whose objects are
triples of a representation           T     of   STLC ,   a family of sets indexed by (the set)              T   and
markers     (t1 , t2 ) ∈ T 2 .
     We go back to considering an arbitrary signature                       S   for types. The following are
the corresponding basic categories of interest:

     Denition 3.40 (SCn ).           Given a category             C     think of it as the category            Set
of sets  we dene the category                    SCn     to be the category an object of which is a
triple   (T, V, t)   where   T     is a representation of     V ∈ C T is a T indexed
                                                                   S,   the object
family of objects of C and t is a vector of elements of T of length n. We denote by
SUn : SCn → Set the functor mapping an object (T, V, t) to the underlying set T .
   We have a forgetful functor SCn → T Cn which forgets the representation struc-
ture. On the other hand, any representation T of S in a set T gives rise to a functor
CnT → SCn , which attaches the representation structure.
     The meaning of a term           s ∈ S(n)       as a natural transformation

                                          s : 1 ⇒ SUn : SCn → Set
is now given by recursion on the structure of                      s:
     Denition 3.41     (Canonical Natural Transformation).                        Let   s ∈ S(n)    be a type of
degree   n. Then s      denotes a natural transformation

                                          s : 1 ⇒ SUn : SCn → Set
dened recursively on the structure of                    s   as follows: for   s = α(a1 , . . . , ak )   the image
of a constructor      α∈S          we set

                             s(T, V, t) = α(a1 (T, V, t), . . . , ak (T, V, t))
and for      s=m     with   1≤m≤n                we dene

                                                 s(T, V, t) = t(m) .
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                            Initiality for Typed Syntax and Semantics                ·    65




We call a natural transformation of the form                s ∈ S(n) canonical.
     Canonical natural transformations are used to build                      classic   halfarities; they
indicate context extension (derivation) and selection of specic object types (bre):

     Denition 3.42 (Classic HalfArity over S ).                  The following clauses dene an
inductive set of  classic halfarities, to which we              restrict our attention:

The constant functor          ∗ : R 7→ 1   is a classic halfarity.

Given any canonical natural transformation                     τ : 1 → SUn           (cf. Def. 3.41), the
     point-wise bre module with respect to          τ    (cf. Def. 2.59) of the tautological module
     Θn : R 7→ (Rn , Rn )    (cf. Def. 3.39) is a classic halfarity of degree             n,
                      [Θn ]τ : S -Mnd → LModn (S, Set) ,                R 7→ (R, [Rn ]τ ) .
Given any (classic) halfarityM = (M1 , M2 ) : S -Mnd → LModn (S, Set) of degree
     n                                       τ : 1 → SUn , the point-wise derivation
         and a canonical natural transformation
 of M with respect to τ (cf. Def. 2.57) is a (classic) halfarity of degree n,
                                                      τ
     M τ : S -Mnd → LModn (S, Set) , R 7→ M (R) := (M1 (R), M2 (R)τ ) .
              τ
 Here M (R)      really means derivation of the module, i.e. derivation in the second
 component of M (R).

Given two (classic) halfarities M = (M1 , M2 ) and N = (N1 , N2 ) of degree n,
 which coincide pointwise on the rst component, i.e. such that M1 = N1 . Then
 their product M × N is again a (classic) halfarity of degree n. Here the product
     is really the pointwise product in the second component, i.e.
                                                                
                            M × N : R 7→ M1 (R), M2 (R) × N2 (R) .
     Remark 3.43        (Classic HalfArity, Syntactically).               We can represent a classic
halfarity of degree       n ∈ N over a signature S        for types in a purely syntactic manner:
such a halfarity is determined by a list of the form

                                     [(t1 , s1 ), . . . , (tk , sk )] ,
where      ti   are vectors of nite length of elements of          S(n)      and   si ∈ S(n).   Such a list
corresponds precisely to the classic halfarity

                                  R 7→ [Rn ]ts11 × . . . × [Rn ]tskk .
We use      weighted sets   as indexing sets for families of arities. The weight denotes the
degree of the corresponding arity.

   Denition 3.44        (Weighted Set).      A weighted set is a set           J    together with a map
d : J → N.
     An arity of degree     n ∈ N for terms over an algebraic signature S                        is a pair of
functors from        S monads to modules in LModn (S, Set). The degree n                       corresponds
to the number of indices of its associated constructor. As an example, the arities
of   Abs   and    App   of Ex. 1.3 are of degree     2,   cf. Ex. 3.47.

  Denition 3.45          (TermArity, Signature over            S ).     A   classic arity α over S of
degree n is a pair
                                                        
                                      s = dom(α), cod(α)
                                                    Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
66      ·     B. Ahrens




of halfarities over      S   of degree    n   such that

dom(α) is classic and

cod(α) is of the form          [Θn ]τ    for some natural transformation         τ   as in Def. 3.42.

We write     dom(α) → cod(α)         for the arity    α,   and

                                     dom(α, R) := dom(α)(R)
(and similarly for the codomain functor              cod). Any classic arity is thus of the form
given in Disp. (3.6). Given a weighted set             (J, d), a termsignature Σ over S indexed
by (J, d) is a J -family Σ       of algebraic     arities over S , the arity Σ(j) being of degree
d(j) for any j ∈ J .
     Finally, a   typed signature    is a pair of a signature for types and a signature for
terms over those types:

  Denition 3.46 (Typed Signature). A typed signature is a pair (S, Σ) consisting
                       S and a termsignature Σ (indexed by some weighted set)
of an algebraic signature
over S .

     Example 3.47 (TLC,        Ex. 1.3 continued).         The terms of the simply typed lambda
calculus over the type signature of Ex. 3.2 are given by the arities

                                   abs : [Θ]12 → [Θ]1;2 ,
                                  app : [Θ]1;2 × [Θ]1 → [Θ]2            ,
both of which are of degree           2    we use the convention of Rem. 3.33. The outer
lower index and the exponent are to be interpreted as de Bruijn variables, ranging
over types.       They indicate the bre (cf. Def. 2.59) and derivation (cf. Def. 2.57),
respectively, in the special case where the corresponding natural transformation
is given by a natural number as in Def. 3.41. In particular, contrast that to the
signature for the simplytyped lambda calculus we gave in Sect. 3.2, Ex. 3.23. The
dierence is that now similar arities which dier only in an object type parameter,
are grouped together, whereas this is not the case in Ex. 3.23.
     Those two arities can in fact be considered over any algebraic signature                    S   with
an arrow constructor, in particular over the signature                  SPCF   (cf. Ex. 3.48).

  Example 3.48 (Ex. 3.8 continued).                We continue considering       PCF. The signature
SPCF for its types is given in Ex. 3.4.           The termsignature of        PCF is given in Fig. 2:
it consists of an arity for abstraction and an arity for application, each of degree
2, an arity (of degree 1) for the xed point operator, and one arity of degree 0 for
each logic and arithmetic constant  some of which we omit:
     Our presentation of       PCF   is inspired by Hyland and Ong's [HO00], who  simi-
larly to Plotkin [Plo77]  consider, e.g., the successor as a constant of arrow type.
As an alternative, one might consider the successor as a constructor expecting a
term of type      ι   as argument, yielding a term of type         ι.   For our purpose, those two
points of view are equivalent.

     3.3.2  Representations of Typed Signatures. A representation of a typed signa-
ture   (S, Σ) is given by a representation of S (in a set) and a representation of Σ in
a suitable monad:

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                           Initiality for Typed Syntax and Semantics             ·    67




                                   abs : [Θ]12 → [Θ]1⇒2 ,
                                   app : [Θ]1⇒2 × [Θ]1 → [Θ]2 ,
                                   Fix : [Θ]1⇒1 → [Θ]1 ,
                                     n : ∗ → [Θ]ι         for   n∈N
                                 Succ : ∗ → [Θ]ι⇒ι
                                 Pred : ∗ → [Θ]ι⇒ι
                                 Zero? : ∗ → [Θ]ι⇒o
                                 condι : ∗ → [Θ]o⇒ι⇒ι⇒ι
                                  T, F : ∗ → [Θ]o
                                       .
                                       .
                                       .




                                 Fig. 2.   Term Signature of       PCF

  Denition 3.49 (Representation of a Signature over S ).                      Let   (S, Σ)   be a typed
signature. Arepresentation R of (S, Σ) is given by
an  S monad P and
for each arity α of Σ,    a morphism (in the large category of modules)

                                 αR : dom(α, P ) → cod(α, P ) ,
  such that   π1 (αR ) = idP .
In the following we also write     R   for the   S monad         underlying the representation      R.
Note that the representation of        S   is hidden in the        S monad P .
  A   morphism of representations accordingly consists of a morphism of                        represen-
tations ofS together with a morphism of representations of Σ, that is,                         a monad
morphism that is compatible with the term representations:

 Denition 3.50 (Morphism of Representations). Given representations P and R
                  (S, Σ), a morphism of representations f : P → R is given by a
of a typed signature
morphism of S monads f : P → R, such that, for any arity α of Σ, the following
diagram of module morphisms commutes:


                          dom(α, P )
                                                 αP             / cod(α, P )

                           dom(α,f )                              cod(α,f )
                                                                  
                          dom(α, R)                             / cod(α, R).
                                                 αR

Again the morphism of representations of              S    is hidden in the morphism of            S
monads.




                                                 Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
68      ·          B. Ahrens




     Remark 3.51.           Taking a 2-categoric perspective, the above diagram can be read
as an equality of 2-cells




                         dom(α,P )                                              dom(α,P )


                                  αP
                                                                                          df
                                                                                                           
               P         cod(α,P )                / IdSet     =      P          ∗
                                                                               f dom(α,R)                 / IdSet ,
                                                   A                                                         A
                                  cf                                                      f ∗ αR

                        f ∗ cod(α,R)                                           f ∗ cod(α,R)




where we write         df    and    cf    instead of        dom(α, f )
                                                   cod(α, f ), respectively.
                                                                         and
                                                 LModn (S, Set)  where n is the
     The diagram of Def. 3.50 lives in the category
degree of α  where objects are pairs (P, M ) of a S monad P of S -Mndn and a
module M over P . The above 2cells are morphisms in the category Mod(Pn , Set),
obtained by taking the second projection of the diagram of Def. 3.50. Note that for
easier reading, we leave out the projection function and thus write                                         dom(α, R)   for
the   Rn module       of   dom(α, R),            i.e. for its second component, and similar elsewhere.

     Representations of            (S, Σ)      and their morphisms form a category.

     Remark 3.52.           We obtain Zsidó's category of representations [Zsi10, Chap. 6] by
restricting ourselves to representations of                        (S, Σ) whose type representation is the
initial one.        More, precisely, a signature                  (S, Σ) maps to a signature, say, Z(S, Σ)
over the initial set of sorts             Ŝ   in the sense of Zsidó (cf. Sect. 3.2 and [Zsi10, Chap. 6]),
obtained by unbundling each arity of higher degree into a family of arities of degree
0.   For instance, the signature of Ex. 3.47 maps to the signature given in Ex. 3.23.
Representations of this latter signature in the sense of Sect. 3.2 then are in oneto
one correspondence to representations in the sense of this section of the signature
of Ex. 3.47        over the initial representation Ŝ of sorts,                 via the equivalence explained
in Rem. 3.37.

     3.3.3     Initiality.    We have all the ingredients to state and prove an initiality the-
orem for typed signatures:

   Theorem 3.53: For any typed signature (S, Σ), the category of representations
of (S, Σ) has an initial object.
Proof.       The proof consists of the following steps:

(1) nd the initial representation                    Ŝ    of the type signature           S;
(2) dene the monad                Σ̂   of terms specied by          Σ   on the category             SetŜ ;
(3) equip the         S monad Σ̂              with a representation structure of                    Σ,   yielding a repre-
      sentation      Σ̂ of (S, Σ);
(4) for any representation                R of (S, Σ), give a morphism of representations iR : Σ̂ →
      R;
(5) prove uniqueness of                 iR .
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                         Initiality for Typed Syntax and Semantics                         ·     69




  We go through these points:

(1) We have already established (cf. Lem. 3.7) that there is an initial representation
    of sorts, which we call            Ŝ .   Its underlying set is called                   Ŝ   as well.

(2) The term monad we associate to                          (S, Σ)      is the same as Zsidó's [Zsi10, Chap. 6]
    in the sense of Rem. 3.52, i.e. it is the term monad associated to                                         Z(S, Σ).        The
    construction of this monad in a settheoretic setting is described in Zsidó's
    thesis. We will give its denition in a typetheoretic setting.
    In the following the natural transformations                                 τi   are in fact vectors of multiple
    transformations like those in Rem. 2.30 (see also Def. 2.57), iterated by suc-
    cessive composition.          Furthermore we make use of the simplied notation as
    introduced in Not. 2.31.
    We construct the monad which underlies the initial representation of                                              (S, Σ),

                                                         Σ̂ : SetŜ → SetŜ .
    It associates to any set family of variables                            V ∈ SetŜ        an inductive set of terms
    with the following constructors:
    for every classic arity (of degree                         n)
                                   α=          [Θn ]τσ11       × . . . × [Θn ]τσm
                                                                                m
                                                                                  → [Θn ]σ                                     (3.8)

      we have a family of constructors indexed                                  n   times by      t = (t1 , . . . , tn )   as well
                                                Ŝ
      as by the context         V ∈ Set              :

                            τ1 (V,t)                                        τm (V,t)
             αt (V ) : Σ̂              (V )σ1 (V,t) × . . . × Σ̂                       (V )σm (V,t) → Σ̂(V )σ(V,t)
    a family of constructors

                                                     Var(V )t : Vt → Σ̂(V )t
      indexed by contexts and the set                           Ŝ   of sorts.
    The monadic structure is, accordingly, dened in the same way as in [Zsi10],
    by variablesasterms  using the constructor                                     Var    and attening.

(3) The representation structure on the monad                                Σ̂ is dened by currying, and corre-
    sponds to Zsidó's: given an arity                       α   of degree      n in Σ, we must specify a module
    morphism

                                         αΣ̂ : dom(α, Σ̂) → cod(α, Σ̂) ,
    where   dom(α, Σ̂)      and    dom(α, Σ̂)               are modules in            Mod(Σ̂n , Set).        We dene


                                              αΣ̂ (V, t)(a) := αt (V )(a) ,
    that is, the image under the constructor                                α   from the denition of the monad
    Σ̂.   This yields a morphism of modules                             α   of degree       n; note that according to
    Rem. 3.37 it would be equivalent to specify a family                                    αtΣ̂ of module morphisms
    of suitable type, indexed by                t,       which is actually done by Zsidó.

(4) Given any other representation                         R    over a set of sorts          T,    initiality of     Ŝ    gives a
    translation of sorts        g : Ŝ → T .


                                                                 Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
70         ·      B. Ahrens




      The morphism            i : Σ̂ → R on terms is dened by structural recursion.                           Unfolding
      the denition of colax monad morphism, we need to dene, for any context

      V ∈ SetŜ ,     a map of type

                                       iV : ∀ t0 ∈ T, ~g (Σ̂(V ))t0 → R(~g V )t0 .
      Via the adjunction of Def. 2.22 we equivalently dene a map                                    i   as a family

                                         iV : ∀ t ∈ Ŝ, Σ̂(V )t → R(~g V )g(t) .

      Let a ∈ Σ̂(V )t be a              term. In case             a = Var(V )t (v)       is the image of a variable
      v ∈ Vt , we map it to
                                   iV (Var(V )t (v)) := η R (~g V )(g(t))(ctype(v)) .
      Otherwise the term          a = αt (V )(a1 , . . . , ak ) ∈ Σ̂(V )σ(V,t) is mapped to
                          αt (V )(a1 , . . . , ak ) := αR (~g (n)(V, t)) i(a1 ), . . . , i(ak ) .
                                                                                              
                     iV                                                                                                (3.9)

      This map is welltyped: note that                           ~g (n)(V, t) = (~g V, g∗ (t))    by Denition 2.28
                                                        τ
      and      ~g (n)((V, t)τ ) = (~g V, g∗ (t))            , i.e. context extension and retyping permute.
      The axioms of monad morphisms, i.e. compatibility of this map with respect
      to variablesasterms and attening are easily checked: the former is a direct
      consequence of the denition of                         i   on variables, and the latter is proved by
      structural induction.                 This denition yields a morphism                      of representations ;
      consider the arity           α   of   Σ.     For this arity, the commutative diagram of Def. 3.50
      informally reads as follows: one starts in the upperleft corner with a tuple
      of terms, say,          (a1 , . . . , ak )   of   Σ̂.   Taking the upperright path corresponds to

      the translation of the image of this tuple under the map                                     αΣ̂ ,   i.e. under the
      constructor         α
                        Σ̂. The lowerleft path corresponds to the image under the
                              of
                            R
      module morphism α       of the translated tuple (i(a1 ), . . . , i(ak )). The diagram
      thus precisely states the equality of Disp. (3.9). We thus establish that i is (the
      carrier of ) a morphism of representations (g, i) : (Ŝ, Σ̂) → R.

(5)   Uniqueness of the morphism i : (Ŝ, Σ̂) → R is proved making use of the com-
                                                            0 0
      mutative diagram of Def. 3.50. Suppose that (g , i ) : (Ŝ, Σ̂) → R is a morphism
                                                             0
      of representations. We already know that g = g by initiality of Ŝ .
                                                                           0
      By structural induction on the terms of Σ̂ we prove that i = i : using the same
      notation as above, for a = αt (V )(a1 , . . . , ak ) we have

                                                              i(ai )=i0 (ai )
               i0 (a) = αR (i0 (a1 ), . . . , i0 (ak ))              =          αR (i(a1 ), . . . , i(ak )) = i(a) .
      In case      a = Var(v)        is a variable, considered as a term, the fact that both              i and
      i0   are monad morphisms ensures that                          i(Var(v)) = i0 (Var(v)) = η~gRV (ctype(v)).
      Thus we have proved                i = i0 .


The proof shows that the initial morphism to a representation                                      R     depends on the
representation structure on                  R     and not just on the monad                 R   itself. We illustrate
this on the example of the typed signature of                            PCF:


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                         Initiality for Typed Syntax and Semantics               ·      71




  Example 3.54.       Representing the signature of            PCF   in the untyped lambda cal-
culus leaves one with several choices to take, e.g., as to how to translate the xed
point operator    Fix.   To represent   Fix   in   ULC,   one must give a unary operation on
ULC.    Reasonable from the semantic viewpoint are, e.g., the representations

                      x 7→ App(Y, x)           or         x 7→ App(Θ, x) ,                           (3.10)

using, e.g., one of the xedpoint combinators

                  Y := λf.(λx.f (xx))(λx.f (xx))              (Curry)

                    Θ := (λx.λy.(y(xxy)))(λx.λy.(y(xxy)))               (Turing).

By initiality, those two representations yield two dierent compilations of PCF to
ULC, mapping a PCF term of the form Fix(f ) to Y(f ) = App(Y, f ) and Θ(f ) =
App(Θ, f ), respectively. The representation module morphisms thus constitute the
                               0
extra structure φ, ψ and ψ mentioned in Sect. 1.1. A complete translation is
given in Sect. 9.

3.4     Logics and Logic Translations
In the style of the CurryHoward isomorphism, we consider propositions as types
and proofs of a proposition as terms of that type. In this example we present the
typed signatures of two dierent logics,

Classical propositional logic, called        CPC, and
Intuitionistic propositional logic, called     IPC.
According to our main theorem each of those signatures gives rise to an initial rep-
resentation, a logical type system. We then use the     iteration principle on CPC in
order to specify a translation    of propositions and their proofs from CPC to IPC.
The translation we specify      is actually the propositional fragment of the Gödel
Gentzen negative translation     [TvD88, Def. 3.4].

  3.4.1     Signatures of Classical and Intuitionistic Logic.             We present typed signa-
tures for classical and intuitionistic propositional logic. Their respective signatures
for types    propositions    are the same: let     P    denote a set of atomic formulas. The
types    propositions  of classical (    CPC) and intuitionistic (IPC) propositional
logic are given by the following algebraic signature:

                 P := {p : 0,   > : 0,     ∧ : 2,    ⊥ : 0,      ∨ : 2,       ⇒: 2} .
where for any atomic formula        p∈P     we have an arity         p : 0.    We call   P̂   the initial
representation as well as its underlying set, i.e. the propositions of             CPC and IPC.
For the set P̂ we    use inxed binary constructors. Note that negation is dened as
¬A ≡ A ⇒ ⊥.
  3.4.1.1     Signature of   CPC.   For the    terms     of   CPC, each inference rule is given
by an arity. In Fig. 3 (p. 72), the inference rules and their corresponding arities
are presented.      Each inference rule corresponds to a (family of ) term                    proof    
constructor(s), where inference rules without hypotheses are constants. Note that
the initial representation automatically comes with an additional inference rule

                                                         var
                                          Γ, A ` A
                                               Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
72       ·         B. Ahrens




                          Inference Rule                                               Arity


                                      >I                                           >I : ∗ → [Θ]>
                               Γ`>
                               Γ`⊥
                                   ⊥I                                            ⊥I : [Θ]⊥ → [Θ]1
                               Γ`A
                       Γ`A   Γ`B ∧
                                   I                                       ∧I : [Θ]1 × [Θ]2 → [Θ]1∧2
                         Γ`A∧B
                          Γ ` A∧B ∧
                                    E1                                          ∧E1 : [Θ]1∧2 → [Θ]1
                          Γ`A
                          Γ ` A∧B ∧
                                    E2                                          ∧E1 : [Θ]1∧2 → [Θ]2
                          Γ`B
                        Γ, A ` B
                                 ⇒I                                             ⇒I : [Θ]12 → [Θ]1⇒2
                           Γ`A⇒B
                    Γ`A⇒B              Γ`A ⇒
                                            E                              ⇒E : [Θ]1⇒2 × [Θ]1 → [Θ]2
                        Γ`B
                          Γ`A     ∨I1                                           ∨I1 : [Θ]1 → [Θ]1∨2
                          Γ ` A∨B
                          Γ`B     ∨I2                                           ∨I2 : [Θ]2 → [Θ]1∨2
                          Γ ` A∨B
         Γ`A∨B             Γ, A ` C             Γ, B ` C
                                                           ∨E         ∨E : [Θ]1∨2 × [Θ]13 × [Θ]23 → [Θ]3
                           Γ`C
                                         EM                                      EM : ∗ → [Θ]¬1∨1
                         Γ ` ¬A ∨ A

                           Fig. 3.     Inference Rules of       CPC and their Arities
corresponding to the monadic operation                     η,   i.e. to the variablesasterms construc-
tor. Analogously to Rem. 3.24, it is not necessary, using our approach, to specify
this inference rule explicitly by an arity in the term signature of the logic under
consideration; any logic we specify via a typed signature automatically comes with
this rule.

     3.4.1.2       Signature of      IPC.   The type signature and thus the formulas of intu-
itionistic propositional logic             IPC     are the same as for            CPC.    However, the     term
signature is missing the arity EM for excluded middle.

     3.4.2Translation via Initiality. The translation of propositions (_)g : P̂ → P̂ ,
i.e. on the type level, is specied by a representation g of the algebraic signature P
in the set P̂ . According to Def. 3.3 we must specify, for any arity s : n ∈ N of P , a
map towards P̂ taking a suitable number of arguments in P̂ ,

                                                  sg : P̂ n → P̂ .
There is, of course, a canonical such map for each arity  but this would only give
us the identity morphism on              P̂ .   We represent      P   in   P̂   not by this identity represen-
tation, but in such a way that we obtain the GödelGentzen negative translation:

             pg := ¬¬p,        >g := ¬¬>,          ∧g := ∧,        ∨g := (A, B) 7→ ¬(¬A ∧ ¬B),
               g                 g
             ⇒ := (⇒),         ⊥ := ¬¬⊥ .

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                              Initiality for Typed Syntax and Semantics         ·    73




The proofs of    IPC are given by the signature of CPC without the classical axiom
EM. We represent EM in       IPC by giving, for any proposition A, a term of type
¬(¬¬A ∧ ¬A),        e.g.,

                                                 var                                      var
            ¬¬A ∧ ¬A ` ¬¬A ∧ ¬A             ¬¬A ∧ ¬A ` ¬¬A ∧ ¬A
                                    ∧E1                                  ∧E2
            ¬¬A ∧ ¬A ` ¬¬A                  ¬¬A ∧ ¬A ` ¬A ⇒
                                                                    E
                             ¬¬A ∧ ¬A ` ⊥                     ⇒I
                                       ` ¬¬A ∧ ¬A ⇒ ⊥
As another example, we give a representation of ∨I1 , that is, for any proposition A
                                g         g      g
and B , we give a term of type A → ¬(¬A ∧ ¬B ):

                                           Ag
                                          ¬¬Ag
                                                      ∨I1
                                       ¬¬Ag ∨ ¬¬B g
                                                      De Morgan
                                       ¬(¬Ag ∧ ¬B g )
Here the proof of      Ag → ¬¬Ag           and of the used De Morgan law are abbreviations
for longer proofs in        IPC.     We leave it up to the reader to nd representations in
IPC for the other arities.
     3.4.3   Remarks.       This representation of the signature of       CPC in IPC yields the
(propositional fragment of the) GödelGentzen translation of propositions specied
in Troelstra and van Dalen's book [TvD88, Def. 3.4], denoted on propositions with
the same name as its specifying representation,

                                             (_)g : P̂ → P̂ .
Our translation of terms shows that any provable proposition in                       CPC   translates
to a provable proposition in           IPC,    since we provide the corresponding proof term
via our translation:

                                     Γ `C A     implies   Γg `I Ag .
However, a logic translation           t   from a logic   L   to another logic   L0   should certainly
satisfy an   equivalence      of the form

                               Γ `L A       if and only if     Γt `L0 At .
Our framework does            not    ensure the implication from right to left, and is thus
decient from the point of view of logic translations.
     Another important property of logics is normalization through cut elimination.
This aspect can be treated using the techniques presented in Sect. 5, where we
integrate    reduction rules        into the notion of signature and their representations as
presented in this chapter.


4.     REDUCTIONS FOR UNTYPED SYNTAX
We now would like to consider not just the                terms    (and types) of a language, but
also   reductions   on the terms. As an example, suppose we would like to equip the
untyped lambda calculus with the reduction relation generated by the beta rule
given in Disp. (A.1). We could produce the syntax associated to the signature via


                                                    Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
74      ·      B. Ahrens




the universal property explained in the preceding section  possibly in a com-
puter implementation thereof  and dene a suitable relation on the terms of the
language    a posteriori.
     However, in this way we would not have any guarantee concerning compatibility
of substitution with respect to this reduction relation. Furthermore, how could we
ensure any compatibility of a translation from the initial representation to another
term language, equipped with some reduction rules, specied via the iteration prin-
ciple? There would not be any systematic way of doing so, we would need to check
manually for each translation we consider.
     The solution to this problem is to integrate reduction rules into signatures and the
models of those signatures. Indeed, instead of considering reduction rules for just
the initial representation of a signature, say,         Σ, we dene inequations over Σ, which
specify rules for    each   representation of     Σ.   However, not all of the representations
of   Σ satisfy those rules; we dene a satisfaction predicate on        the representations
of   Σ, to pick out the representations that satisfy those rules.
     In order to dene the satisfaction predicate, we need to consider representations
whose codomain (read: the codomain of the underlying monad) is not the category
of plain sets, but of sets with a structure suitable to express relations between its
elements. The following monadic models come to mind:

X    M : Set → Set     Terms modulo relations by quotienting
     We reject the idea of quotienting by the congruence relation generated by a set
     of inequations on the grounds that we want to avoid adding a          symmetry       rule and
     thus loose the information of      direction   of a reduction

X    M : Pre → Pre     Monads on preordered sets
     While the use of monads on preordered sets allows to retain directions of reduc-
     tions, it would necessitate to consider    preordered contexts. However,             contexts
     usually are given by    unstructured sets of variables.
X M : Set → Pre            Relative Monads from sets to preordered sets
     Relative monads from sets to preorders avoid the problems one encounters with
     the aforementioned approaches. As shown in Sect. 2.4.1, the mediating functor
     to use is the functor   ∆ : Set → Pre.
Before going into more detail concerning the models of signatures with inequations,
we have a closer look at those signatures themselves.                Signatures should carry
information about

     Syntax.   the terms, optionally typed over a set of sorts, and

     Semantics. reductions     on the terms.

Accordingly, we introduce a notion of             2signature.   A 2signature   (Σ, A)   consists
of a (higherorder) signature       Σ    which we also call 1signature from now on, to
emphasize the existence of a second level, the            semantic level  which species the
terms of a language, as well as a set         A   of   inequations over Σ. Each inequation of
A    species a reduction rule.
     We borrow the terms 1signature and 2signature from T. Hirschowitz [Hir]:
they are motivated by the point of view of Categorical Semantics. There, types and
terms of a language are modelled as the objects and morphisms of a category. Fur-


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                     Initiality for Typed Syntax and Semantics          ·     75




thermore, reductions between terms may be modelled through 2cells. In this way,
a 1signature species a 1category, whereas a 2signature species a 2category.
  As the 1signature which underlies a 2signature, we may choose any of the
notions of signature dened in the preceding chapters (cf. Defs. 3.18, 3.46).               For
this chapter, however, we restrict ourselves to          untyped    syntax with reductions,
allowing us to employ a simple notion of 1signature. The next chapter integrates
reductions and types.
  While we present 1signatures from two perspectives, a syntactic one and a se-
mantic one, we only present inequations semantically.              We refer to Sect. 10.2 for
thoughts about the syntactic aspect.


4.1   1Signatures
We start out by dening   1signatures   in two dierent ways, once syntactically, and
once in terms of pairs of functors between suitable categories.
  The syntactic description of arities is actually the same as in Sect. 3.2, even
simpler: since we only consider    untyped   syntax, we just need to specify the number
of arguments of a constructor, and, for each argument, the number of variables
bound in it:

  Denition 4.1    (Classic Arity, Signature).      A   classic arity     is given by a list of
natural numbers. The length of the list indicates the number of arguments of its
associated constructor, whereas the ith component of the list species the number
of variables bound in the   ith   argument. A     classic signature       is given by a family
of arities.

  Example 4.2 (Untyped Lambda Calculus).            The signature of the untyped lambda
calculus is given by

                         ΣULC := {app : [0, 0] ,        abs : [1]} .
For the semantic denition of arities, we dene a suitable category of monads and
a large category of modules. As discussed at the beginning of the chapter, we use
relative   monads and modules over relative monads.
  We start by giving a simplied version of the denition of morphism of relative
monads, to which we restrict ourselves throughout this chapter.                  It is obtained
from Def. 2.87 by restricting the vertical functors      G   and   G0   to the identity functor.
Furthermore we will haveF = F 0 , and the natural transformation N is the identity
transformation. Given two relative monads P and Q on F : C → D , a (simple)
morphism of relative monads is a family of morphisms τc ∈ D(P c, Qc) that is
compatible with the monadic structure:

 Denition 4.3 (Morphism of Relative Monads). Given two relative monads P
and Q from C to D on the functor F : C → D, a morphism of monads from P to
Q is given by a collection of morphisms τc ∈ D(P c, Qc) such that the following




                                             Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
76        ·      B. Ahrens




diagrams commute for all suitable morphisms                        f:
                                     σ P (f )                                 ηcP
                               Pc                / Pd          Fc                     / Pc

                           τc                       τd                                   τc
                                                                            ηcQ
                                                                                     ! 
                               Qc                / Qd                                   Qc.
                                     Q
                                    σ (τd ◦f )

As a consequence from these commutativity properties the family                                     τ is a natu-
ral transformation between the functors induced by the monads                                      P and Q (cf.
Rem. 2.80).

 Denition 4.4 (Category of Relative Monads on F ). Given a functor F : C → D,
we dene the category RMon(F ) to be the category whose objects are relative
monads on F . A morphism from P to Q in RMon(F ) is a morphism as in Def. 4.3.

     There is an adjunction between relative monads on                            ∆   and monads on sets:

  Lemma 4.5 (Adjunction between Mon(Set) and RMon(∆)): The functors (with
object functions) dened in Lem. 2.83 give rise to an adjunction
                                                         ∆∗
                                                                        (
                               Mon(Set) h                ⊥                  RMon(∆) .
                                                         U∗

Proof.        The isomorphism       ϕP,Q : RMon(∆)(∆∗ P, Q) ∼
                                                            = Mon(Set)(P, U∗ Q)                         is dened
by applying the adjunction of Lem. 2.18 in each morphism of the family underlying a
morphism of (relative) monads. Commuting diagrams are not modied by applying
this adjunction. Naturality of              ϕ    is trivial.

   Denition 4.6 (Large Category of Modules). Given a functor F : C → D and a
category E , we dene the category LRMod(F, E) to be the category whose objects
are pairs (P, M ) of a relative monad P ∈ RMon(F ) and a relative P module M
with codomain E . A morphism to another such (Q, N ) is a pair (h, f ) of a morphism
h : P → Q in RMon(F ) and a morphism of P modules f : P → h∗ Q to the pullback
of Q along h (cf. Sect. 2.4.2).
   For any monad P on F there is the injection functor

                       IP : RMod(P, E) → LRMod(F, E),                         f 7→ (id, f ) .
     A   halfarity   associates a       P module towards the category Pre of preorders to any
relative monad        P   on   ∆:
     Denition 4.7     (HalfArity).            A   halfarity a   is a functor

                                    a : RMon(∆) → LRMod(∆, Pre)
that is preinverse to the forgetful functor.

     Similarly to the preceding sections we restrict our attention to                         classic halfarities:
     Denition 4.8 (Classic HalfArity).                  The following clauses dene the inductive
set of  classic halfarities:
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                          Initiality for Typed Syntax and Semantics             ·       77




Θ  : P 7→ (P, P ), the tautological module, is classic;
                                        0                 0
if M is classic, so is its derivation M : P 7→ (P, M (P ) );

if M and N are classic, so is their product M × N : P 7→ (P, M (P ) × N (P ));

the constant halfarity ∗ : P 7→ 1 is classic.

Classic halfarities as dened in Def. 4.8 are in onetoone correspondence to classic
arities as dened in Def. 4.1:

  Remark 4.9.      We use the notation dened in Not. 2.103. More generally, given a
list of natural numbers    s = [n1 , . . . , nm ],   we write   M s := M n1 × M n2 × . . . × M nm .
  The same notation is used for morphisms, i.e.                 given a morphism of Rmodules
f : M → N,     we write

                           f s := f n1 × . . . × f nm : M s → N s .
Thus any list of natural numbers species uniquely a classic halfarity, the empty
list denoting the terminal module         ∗ : R 7→ 1.
  Denition 4.10 (Arity).        An   arity s is a pair s = (dom(s), cod(s)) of halfarities
                      dom(s), cod(s) : RMon(∆) → LRMod(∆, Set) .
We write    s = dom(s) → cod(s),         and    dom(s, P ) := dom(s)(P )            (and similarly for
cod).
  Denition 4.11      (Classic Arity, 1Signature).             A   classic arity   is an arity of the
form

                                          dom(s) → Θ
such that    dom(s)   is a classic halfarity. Any classic arity as in Def. 4.1 uniquely
species a classic arity by specifying its domain according to Rem. 4.9.                            A   1
signature    is a family of classic arities, or, equivalently according to Rem. 4.9, a
family of lists of natural numbers.

  Example 4.12     (Untyped Lambda Calculus).                  The 1signature       ΣULC   of the un-
typed lambda calculus, already given syntactically in Ex. 4.2, is given by the two
arities

                        app := Θ × Θ → Θ ,                abs := Θ0 → Θ .
4.2     Representations of 1Signatures
A representation of a classic arity     s in a monad P         is a module morphism       dom(s, P ) →
P.    More generally:

  Denition 4.13 (Representation of an               Arity).    A representation of an arity        s=
dom(s) → cod(s) in a monad P on ∆ is                 a morphism      M   of   P modules
                                M : dom(s, P ) → cod(s, P )
in the category   LRMod(∆, Set), such that π1 (M ) = id. By abuse of notation, we
also denote by    M the second projection of M , i.e. we consider M ∈ RMod(P, Set).
  A representation of a signature is given by a relative monad on                     ∆   and a repre-
sentation of each arity in this monad:

                                                     Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
78      ·       B. Ahrens




  Denition 4.14 (Representation of a 1Signature).                           A   representation R of a sig-
nature Σ is given by
a monad        P   on   ∆   and

a representation            sR : dom(s, P ) → cod(s, P )            of each arity          s ∈ Σ      in   P   as in
     Def. 4.13.

Given a representation               R,   we denote its underlying monad by                R   as well.

     For any signature           Σ   as in Def. 4.11, we have representations of                   Σ   in monads
on    Set   (cf. Def. 3.25) and in relative monads on                ∆    (cf. Def. 4.14). The following
denition links those representations:

    Denition 4.15 (Reps. in Relative Monads and Monads). To any representation
of a classic signature Σ in a relative monad R as dened in Def. 4.14 we associate
a   representation of Σ in the monad U∗ R (cf. Lem. 4.5) according to the denition
of representation of Def. 3.25, by postcomposing with the forgetful functor from
preorders to sets.
     Conversely, to any representation of                Σ    in a monad Q over sets we associate a
representation of        Σ   in the relative monad            ∆∗ Q over ∆, by postcomposing with ∆.
More precisely, an arity             s = [s1 , . . . , sn ] ∈ Σ and a representation of s in Q, say,
                                                 sQ : Qs → Q ,
with    Qs := Qs1 × . . . × Qsn ,           we have to give a morphism of modules

                                      ∆∗ Qs1 × . . . × ∆∗ Qsn → ∆Q∗ ,
that is, a family of monotone morphisms in the category                           Pre.   However, the domain
module is isomorphic to               ∆∗ Qs ,   hence postcomposing the map                sQ   with   ∆    does the
job,

                                            ∆∗ sQ : ∆∗ Qs → ∆∗ Q ,
and    ∆∗ sQ   obviously has the necessary commutation property with respect to sub-
stitution.

     Example 4.16    (Ex. 4.12 continued).               A representation         P   of   ΣULC   is given by

                             ∆
a monad        P : Set → Pre and
two        morphisms of P modules             in   RMod(P, Pre),
                                 app : P × P → P          and     abs : P 0 → P .
Morphisms of representations are monad morphisms which commute with the rep-
resentation morphisms of modules:

 Denition 4.17 (Morphism of Representations). Let P and Q be representations
                  Σ. A morphism of representations f : P → Q is a morphism of
of a classic signature
monads f : P → Q such that the following diagram commutes for any arity s ∈ Σ:


                                            dom(s, P )
                                                             sP      /P

                                             dom(s,f )                    f
                                                                     
                                            dom(s, Q)              / Q.
                                                             sQ

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                               Initiality for Typed Syntax and Semantics            ·           79




The meaning of those diagrams might become clearer when we consider the example
of the untyped lambda calculus. In line with the abuse of notation mentioned in
Def. 4.13, we omit the rst component of objects and morphisms in                    LRMod(∆, Set):
  Example 4.18 (Ex. 4.16 continued). Let P and R be two representations of ΣULC .
A morphism from P to R is given by a morphism of monads f : P → R such that
the following diagrams of P module morphisms commute:

                       appP
         P ×P                       /P                                       P0
                                                                                      absP           /P

         f ×f                              f                                f0                              f
                                                                                                     
    f ∗ (R × R)                    / f ∗R                                  f ∗ R0                  / f ∗ R.
                     f ∗ (appR )                                                    f ∗ (absR )

To make sense of these diagram it is necessary to recall the constructions on modules
of Sect. 2.4.2. The diagrams live in the category                    RMod(P, Pre). The vertices are
obtained from the tautological modules                 P   resp. the  Q over the monads P resp. Q
                           Q) and derivation functors as well as by the use of
by applying the pullback (for
                             P modules into Pre. The vertical morphisms are
the product in the category of
module morphisms induced by f , to which  on the lefthand side  functoriality
of derivation and products are applied. Furthermore instances of Lem. 2.106 and
2.107 are hidden in the lower left corner. The lower horizontal morphism makes
use of the functoriality of the pullback operation.

    Denition 4.19   (Category of Representations).                   Representations of   Σ      and their
morphisms form a category          Rep∆ (Σ).
  Lemma 4.20 (Adj. between Reps. in Rel. Monads and Reps. in Monads): The
assignment of Def. 4.15 extends to an adjunction between the category of represen-
tations in relative monads on ∆ and the category of representations in monads on
sets (cf. Def. 3.27):
                                                   ∆∗
                                                                (
                            Rep(Σ) h               ⊥                Rep∆ (Σ) .
                                                   U∗

  Lemma 4.21 (Initiality for 1Signatures): The category of representations of
a signature Σ in relative monads as dened in Def. 4.19 has an initial object. Its
underlying monad associates, to any set of variables, the set of terms of Σ, equipped
with the equality preorder.
Proof.   This is a direct consequence of Lem. 2.19 which says that left adjoints pre-
serve colimits  thus, in particular, initial objects , applied to the adjunction of
Lem. 4.20.


4.3    Inequations
Consider the beta rule of lambda calculus,

                                    λM (N ) ; M [∗ := N ] .

                                                     Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
80        ·   B. Ahrens




In our formalism, abstraction and application are considered as morphisms of mod-
ules (cf. Ex. 2.95), and so is substitution (cf. Def. 2.110). This suggests to dene
(in)equations over a 1signature        Σ   as   parallel pairs   of module morphisms, indexed
by representations of     Σ.   Put dierently, an (in)equation associates a parallel pair of
module morphisms to any representation of               Σ.   Hirschowitz and Maggesi [HM07b]
specify equations through such pairs of (indexed) module morphisms over (plain)
monads. We adapt their denition to our use of               relative   monads and modules over
such monads. Afterwards we simply interpret a pair of halfequations as                 inequation
rather than equation.

  Denition 4.22 (Category of HalfEquations, [HM07b]). Let Σ be a signature.
A Σmodule U is a functor from the category of representations of Σ to the category
LRMod(∆, wPre) commuting with the forgetful functors to the category of relative
monads over ∆:


              Rep∆ (Σ)
                                             U                     / LRMod(∆, wPre)


                                       &    v
                                      RMon(∆).
Such a     Σmodule U associates, to any representation of Σ with underlying monad
P,   a module over  P.
     We   dene a morphism of Σmodules to be a natural transformation which be-
comes the identity when composed with the forgetful functor. We call these mor-
phismshalfequations. These denitions yield a category which we call the category
of Σmodules (or the category of halfequations). We sometimes write
                                         R
                                        UX := U (R)(X)
for the value of a   Σmodule at the representation R              and the set   X.   Similarly, for
a halfequation    α : U → V we write
                                  R               R
                                 αX := α(R)(X) : UX → VXR .
  Remark 4.23. We dene Σmodules over the signature Σ as functors into the
category LRMod(∆, wPre), whose objects are modules with codomain category wPre
instead of Pre to accommodate an important example: recall that substitution of
one variable (cf. Def. 2.110) is not necessarily monotone in the second argument.
Thus, in order to build a halfequation from this substitution (cf. Def. 4.27), we
need to use the category       wPre   as codomain category.

  Remark 4.24. A halfequation α from Σmodule U to V associates, to any
representation  R, a morphism of Rmodules αR : U (R) → V (R) in RMod(R, wPre)
such that for any morphism f : P → R of representations of Σ the following diagram




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                             Initiality for Typed Syntax and Semantics           ·     81




commutes:


                        (P, U (P ))
                                                   αP               / (P, V (P ))


                         (f,U (f ))                                    (f,V (f ))


                                                                      
                (R, f ∗ (U (R)))                                    / (R, f ∗ (V (R))) .
                                                   αR

  Remark 4.25.          PierreLouis Curien suggested the following alternative denition
of a halfequation, where its domain and codomain only depend on     the monad
underlying each representation : domain and codomain are specied by functors U
and V on the category RMon(∆), and a halfequation α from U to V is given by a
natural transformation

                                         α : U ◦ π1 → V ◦ π1 ,
                    ∆
where     π1 : Rep (Σ) → RMon(∆)              is the forgetful functor.        Indeed, in all the ex-
amples of halfequations we consider, the domain and codomain                          Σmodules     only
depend on the monads underlying a representation, not the representation structure
itself. Both variants, the one presented here in detail as well as the one suggested
by Curien, are implemented in our             Coq   library.

  Given a 1signature          Σ,     we restrict ourselves to      classic   inequations:     these are
inequations whose codomain              Σmodule     is of a specic form.           The restriction to
these inequations allows us to ensure a technical condition which we prove, for
classic inequations, in Lem. 4.35. Analogously to the preceding chapters, we only
write the second component of objects in the large category                         LRMod(∆, wPre)     of
modules.

  Denition 4.26        (Classic      ΣModule).        We call   classic   any     Σmodule   satisfying
the following inductive predicate.

The map     Θ̂ : R 7→ πd
                        1 R (cf. Def. 2.109 and Rem.               4.25) is a classic   Σmodule.
If the    Σmodule M : R 7→ M (R) is classic, so is
                                           M 0 : R 7→ M (R)0 .
If   M   and   N   are classic, so is

                                      M × N : R 7→ M (R) × N (R) .
The terminal module            ∗ : R 7→ 1   is classic.

Using the same notation as in Rem. 4.9, any list of natural numbers species
uniquely a classic      Σmodule.
  We now present some particular classic halfequations:

  Denition 4.27.         The substitution operation of Def. 2.110,

                                subst : R 7→ substR : R̂0 × R̂ → R̂
is a halfequation over any 1signature             Σ.   Its domain and codomain are classic.

                                                    Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
82      ·        B. Ahrens




     Example 4.28         (Ex. 4.12 continued).      The map

                  app ◦ (abs × id) : R 7→ appR ◦ (absR × idR ) : R̂0 × R̂ → R̂
is a halfequation over the signature             ΣULC .
     Denition 4.29.         Any arity   s = [n1 , . . . , nm ] ∈ Σ   denes a classic          Σmodule
                                                       n1                nm
                                    dom(s) : R 7→ R          × ... × R         .
An    inequation     is given by a pair of parallel halfequations:

   Denition 4.30 (Inequations, 2Signature). Given a 1signature Σ, a Σinequa-
tion is a pair of parallel halfequations between Σmodules. We write
                                              α≤γ:U →V
for the inequation          (α, γ) with domain U and codomain V .                   A   2signature   is a pair
(Σ, A)      of a 1signature     Σ and a set A of Σinequations.
     Given a 2signature          (Σ, A), we can test whether a given representation R of Σ
satises the inequations of           A. Those representations satisfying any inequation of A
form the category of            representations of (Σ, A):

   Denition 4.31 (Representation of Inequations). A representation of a Σin-
equation α ≤ γ : U → V is any representation R of Σ such that αR ≤ γ R pointwise,
i.e. such that for any set X and any y ∈ U (R)(X),

                                               R        R
                                              αX (y) ≤ γX (y) .
We say that such a representation  R satises the inequation α ≤ γ .
     For a set   A   of   Σinequations, representation of (Σ, A) any representation
                                           we call
of Σ that satises each inequation of A. We dene the category of representations
                                                          ∆
of the 2signature (Σ, A) to be the full subcategory Rep (Σ, A) of the category of
representations of Σ whose objects are representations of (Σ, A).

     Example 4.32         (Ex. 4.28 continued).      We denote by         β   the    ΣULC inequation
                                        app ◦(abs × id) ≤ subst .                                             (β)
We write      (ΣULC , β) := (ΣULC , {β}).        A representation        P    of   (ΣULC , β)   is given by

                            ∆
a monad         P : Set → Pre and
two morphisms of         P modules
                                 app : P × P → P        and        abs : P 0 → P
such that for any set           X   and any   y ∈ P (X 0 )   and   z ∈ PX
                                    appX (absX (y), z) ≤ y[∗ := z] .
4.4     Initiality for 2Signatures
Given a 2signature          (Σ, A), we would like to exhibit an initial object in its associated
category of representations of          (Σ, A). However, we have to rule out inequations
which are never satised, since an empty category obviously does not not have an
initial object. We restrict ourselves to inequations with a classic codomain:

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                    Initiality for Typed Syntax and Semantics            ·     83




     Denition 4.33          (Classic Inequation).          A   Σinequation    is   classic   if its codomain
is classic.

  Theorem 4.34: For any set of classic Σinequations A, the category of repre-
sentations of (Σ, A) has an initial object.
Proof.      The basic ingredients for building the initial representation are given by the
initial representation          ∆Σ̂   in the category     Rep∆ (Σ) (cf. Lem. 4.21) or, equivalently,
by the initial representation             Σ̂   in    Rep(Σ). We call Σ̂ the monad underlying the
representation         Σ̂.
     The proof consists of three steps: at rst, we dene a preorder                       ≤A    on the terms
of   Σ̂,   induced by the set      A of inequations.         Afterwards we show that the data of the
representation         Σ̂     substitution, representation morphisms etc.  is compatible
with the preorder  ≤A in a suitable sense. This will yield a representation Σ̂A                                 of
(Σ, A). Finally we show that Σ̂A is the initial such representation.
 The monad underlying the initial representation:
For any set X , we equip Σ̂X with a preorder A by setting, for x, y ∈ Σ̂X ,



                      x ≤A y        :⇔        ∀R : Rep∆ (Σ, A),         iR (x) ≤R iR (y) ,                   (4.1)

where       iR : ∆Σ̂ → R        is the initial morphism of representations of              Σ,   cf. Lem. 4.21.
We have to show that the map

                                          X 7→ Σ̂A X := (Σ̂X, ≤A )
yields a relative monad on               ∆.    The missing fact to prove is that the substitution
with a morphism

                                   f ∈ Pre(∆X, Σ̂A Y ) ∼
                                                       = Set(X, Σ̂Y )
is compatible with the order                  ≤A :    given any f ∈ Pre(∆X, Σ̂A Y ) we show that
 Σ̂
σ (f ) : Set(Σ̂X, Σ̂Y ) is monotone with                 respect to ≤A and hence (the carrier of ) a
morphism σ(f ) : Pre(Σ̂A X, Σ̂A Y ). We                  overload the inx symbol = to denote
monadic substitution. Suppose x ≤A y ,                      we show

                                          x = f ≤A y = f .
Using the denition of            ≤A ,   we must show, for any representation              R    of   (Σ, A),
                                      iR (x = f ) ≤R iR (y = f ) .
Since iR is a morphism of representations, it is compatible with the substitution of
Σ̂   and    U∗ R ;   we have

                                   iR (x = f ) = iR (x) = iR ◦ f .
Rewriting this equality and its equivalent for                    y   in the current goal yields the goal

                               iR (x) = iR ◦ f         ≤A       iR (y) = iR ◦ f ,
which is true since the substitution of                 R   (whose underlying map is that of     U∗ R) is
monotone in the rst argument (cf. Rem. 2.86) and iR (x)                        ≤R iR (y) by assumption.
We hence have dened a monad                   Σ̂A over ∆.      We interrupt the proof for an important
lemma:

                                                          Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
84      ·     B. Ahrens




     Lemma 4.35:   Given a classic Σmodule V : Rep∆ (Σ) → LMod(∆, wPre) from
the category of representations of Σ in monads on ∆ to the large category of modules
over such monads, we have
      x ≤A y ∈ V (Σ̂)(X)          ⇔     ∀R : Rep∆ (Σ, A),            V (iR )(x) ≤VXR V (iR )(y) ,
where now and later we omit the argument X , e.g., in V (iR )(X)(x).
Proof of Lem. 4.35.        The proof is done by induction on the derivation of  V classic.
The only interesting case is where         V =M ×N              is a product:

 (x1 , y1 ) ≤ (x2 , y2 ) ⇔ x1 ≤ x2 ∧ y1 ≤ y2
                          ⇔ ∀R, M (iR )(x1 ) ≤ M (iR )(x2 ) ∧ ∀R, N (iR )(y1 ) ≤ N (iR )(y2 )
                          ⇔ ∀R, M (iR )(x1 ) ≤ M (iR )(x2 ) ∧ N (iR )(y1 ) ≤ N (iR )(y2 )
                          ⇔ ∀R, V (iR )(x1 , y1 ) ≤ V (iR )(x2 , y2 ) .


 Representing Σ in Σ̂A :
Any arity  s ∈ Σ should be represented by the module morphism sΣ̂ , i.e. by the
representation of s in Σ̂. We have to show that those representations are compatible
with the preorder ≤A . Given x ≤A y in dom(s, Σ̂)(X), we show (omitting the
                 Σ̂
argument X in s (X)(x))


                                      sΣ̂ (x)     ≤A       sΣ̂ (y) .
By denition, we have to show that, for any representation                    R     as before,

                                 iR (sΣ̂ (x))     ≤R       iR (sΣ̂ (y)) .
Since   iR   is a morphism of representations, it commutes with the representational
module morphisms  the corresponding diagram is similar to the diagram of
Def. 4.17. By rewriting with this equality we obtain the goal
                                                                            
                 sR       dom(s)(iR ) (x)         ≤R       sR       dom(s)(iR ) (y) .

This goal is proved by instantiating Lem. 4.35 with the classic                      Σmodule dom(s)
(cf. Def. 4.29) and the fact that          sR    is monotone.          We hence have established a
representation  which we call          Σ̂A      of   Σ   in the monad     Σ̂A .
 Σ̂A satises A:
The next step is to show that the representation              Σ̂A satises A.       Given an inequation

                                          α≤γ:U →V
of A with a classic Σmodule V ,           we must show that for any set                X   and any   x∈
U (Σ̂A )(X) in the domain of α we          have

                                     Σ̂A                    Σ̂A
                                    αX   (x)      ≤A       γX   (x) .                               (4.2)

In the following we omit the subscript            X.   By Lem. 4.35 the goal is equivalent to



             ∀R : Rep∆ (Σ, A),        V (iR )(αΣ̂A (x))         ≤VXR     V (iR )(γ Σ̂A (x)) .       (4.3)


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                   Initiality for Typed Syntax and Semantics          ·    85




Let   R   be a representation of              (Σ, A). We continue by proving Disp.        (4.3) for   R.   By
Rem. 4.24 and the fact that                  iR is also the carrier of a morphism of      representations
of   Σ   from   ∆Σ̂   to   R   (cf. Lem. 4.20) we can rewrite the goal as

                                   αR U (iR )(x)               γ R U (iR )(x) ,
                                                                            
                                                      ≤VXR
which is true since            R   satises   A.
 Initiality of Σ̂A :
Given any representation     R of (Σ, A), the morphism iR is monotone with respect
to the preorders on   Σ̂A and R by construction of ≤A . It is hence a morphism of
representations from Σ̂A to R. Uniqueness of the morphisms iR follows from its
uniqueness in the category of representations of Σ, i.e. without inequations. Hence
Σ̂A is the initial object in the category of representations of (Σ, A).
     Remark 4.36.          Note that the proof of the main theorem uses the equivalence
proved in Lem. 4.35 in               both   directions. The implication from left to right would be
ensured automatically if we had dened             Σmodules to be functors into the category
LRMod(∆, Pre)          instead of       LRMod(∆, wPre). See Rem. 4.23 for an explanation why
we still choose the latter category as codomain category.

     Remark 4.37.          Note that for a classic         Σmodule V       we can actually prove the
implication from left to right of Lem. 4.35 more generally: for any morphism of
representationsf : P → R (not just an initial one as in Lem. 4.35) the module
morphism V (f ) : V (P ) → V (R) is monotone. Again the only interesting case is
where V = V1 × V2 is a product. Let X be a set and x = (x1 , x2 ) and y = (y1 , y2 )
in V (P )(X):

     (x1 , x2 ) ≤V P (y1 , y2 ) ⇔ x1 ≤V1P y1 ∧ x2 ≤V2P y2
                                     ⇒ V1 (f )(x1 ) ≤V1R V1 (f )(y1 ) ∧ V2 (f )(x2 ) ≤V2R V2 (f )(y2 )
                                     ⇔ (V1 (f )(x1 ), V2 (f )(x2 )) ≤V R (V1 (f )(y1 ), V2 (f )(y2 ))
                                     ⇔ V (f )(x1 , x2 ) ≤V R V (f )(y1 , y2 ) .
  Example 4.38 (Ex. 4.32 continued). The only inequation Disp. (β) of the sig-
nature(ΣULC , β) is classic. The initial representation of (ΣULC , β) is given by
the monad ULCβ together with the ULCβ module morphisms Abs and App (cf.
Ex. 2.95) as representation structure.

     We conclude this section with some remarks about generating inequalities, (reg-
ular) monads and           fully     faithful morphisms:

   Remark 4.39 (about Generating Inequations). Given a 2signature (Σ, A) and
a representation R of Σ, the representation morphism of modules sR of any s ∈ Σ
of R is monotone. For the initial representation of (Σ, A) this means that any
relation between terms of Σ which comes from A is automatically propagated into
subterms.       Similarly, the relation on those terms is by construction reexive and
transitive, since we consider representations in monads with codomain                          Pre.
     For the example of            ULCβ     this means that in order to obtain a complete reduction
relation, it is sucient to enforce only one rule by an inequation, which is

                                              (λM )N ≤ M [∗ := N ] .

                                                         Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
86      ·     B. Ahrens




     Remark 4.40    (about Finite Contexts).            Altenkirch et al. [ACU10] character-
ize the untyped lambda calculus as a relative monad on the inclusion functor
i : Fin → Set     from nite sets to sets.        An anonymous referee suggested combin-
ing our viewpoint  syntax as monad over                ∆ : Set → Pre      with Altenkirch et
al.'s one might consider the lambda calculus as a relative monad on the composi-
tion   ∆ ◦ i : Fin → Pre, and, more generally, one might consider representations of
a signature    (Σ, A) over monads on ∆ ◦ i : Fin → Pre. The above theorem remains
true   when replacing monads on ∆ by monads on ∆ ◦ i everywhere. An equivalence
between the theorem thus obtained and our Thm. 4.34 might be established in a
way similar to what Zsidó [Zsi10] does in her PhD thesis: she shows, by means of
adjunctions between the respective categories of models, the equivalence between
the approach of Fiore et al. [FPT99]  based on monoids over nite contexts 
and the approach of Hirschowitz and Maggesi [HM07a], where models are built
from monads on the category          Set,   i.e. over arbitrary contexts.

     Remark 4.41   (about Monads on           Pre).    As mentioned in Sect. 1.5, Ghani and
Lüth [GL03] and Hirschowitz and Maggesi [HM10a] suggest the use of monads
over the category       Pre   of preordered sets for modelling syntax with a rewriting
relation. Indeed, representations of a signature          (Σ, A) could be analogously dened
for such monads.        The above construction of the initial representation of        (Σ, A)
carries over to representations in such monads, thus yielding an initiality result in
which syntax is modelled as monad on             Pre.   It might be interesting to establish a
precise connection  e.g., in form of adjunctions  between the resulting categories
of representations in monads on         Pre   and representations in relative monads on        ∆.
   Remark 4.42 (about Fully Faithful Translations). By construction any mor-
phism  f : P → Q of representations of a 2signature (Σ, A) is faithful, i.e. it sends
related terms x ; y in P (X) to related terms fX (x) ; fX (y) in Q(X). It is natu-
ral to ask whether f is also full, that is, whether each fX : P (X) → Q(X) is a full
functor between the preorders P (X) and Q(X), considered as functors. Explicitly,
this means to ask whether for any x, y ∈ P (X) such that fX (x) ; fX (y) in Q(X)
we have x ; y .


5.     SIMPLE TYPE SYSTEMS WITH REDUCTIONS
This chapter aims to combine the contents of Sects. 3 and 4 in order to obtain an
initiality result for simple type systems with reductions on the term level.                  This
result thus accounts for our example from Sect. 1.1: the translation from              PCF    with
its usual reduction relation to the untyped lambda calculus with beta reduction.
The goal thus is to dene a notion of         signature   and suitable   representations   for such
signatures, such that the types and terms generated by the signature, equipped
with reductions according to the inequations specied by the signature, form the
initial representation. Analogously to the previous chapter, we dene a notion of 2
signature with two levels: a syntactic level specifying types and terms of a language,
and, on top of that, a semantic level specifying reduction rules on the terms.


5.1    1Signatures
From the    syntactic   point of view presented in  3.3.1.1, 1signatures for types and
terms are the same as in Sect. 3, Def. 3.46. We have to adapt the            semantic denition
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                  Initiality for Typed Syntax and Semantics        ·     87




of signatures for terms, however, since we now work with relative monads on                            ∆T
for some set   T     instead of monads over families of sets. The following denition is
the analogue of Def. 3.34, adapted to the use of relative monads:

   Denition 5.1 (Relative S Monad). Given an algebraic signature S , the category
S -RMnd of relative S monads is dened as the category whose objects are pairs
(T, P ) of a representation T of S and a relative monad
                                                        ∆T
                                             P : SetT −→ PreT .
A morphism from          (T, P )   to   (T 0 , P 0 )
                                      is a pair (g, f ) of a morphism of S representa-
tions g : T → T and a morphism of relative monads f : P → P 0 over the retyping
                     0

functor ~g as in Rem. 2.89.
   Given n ∈ N, we write S -RMndn for the category whose objects are pairs (T, P ) of
                                                            T
a representation T of S and a relative monad P over ∆n . A morphism from (T, P )
      0   0                                                                     0
to (T , P ) is a pair (g, f ) of a morphism of S representations g : T → T and a
                                0
monad morphism f : P → P over the retyping functor ~         g (n) dened in Def. 2.28.
    Similarly, we have a large category of modules over relative monads:

   Denition 5.2 (Large Category LRModn (S, D) of Modules). Given a natural
number    n ∈ N, an algebraic signature S and a category D, we call LRModn (S, D)
the category an object of which is a pair (P, M ) of a relative S monad P ∈ S -RMndn
and a P module with codomain D . A morphism to another such (Q, N ) is a pair
(f, h) of a morphism of relative S monads f : P → Q in S -RMndn and a morphism
                                ∗
of relative modules h : M → f N .

    As before, we sometimes just write the module  i.e. the second  component of
an object or morphism of the large category of modules. Given   M ∈ LRModn (S, D),
we thus write M (V ) or MV for the value of the module on the object V .
  A halfarity over S of degree n is a functor from relative S monads to the cate-
gory of large modules of degree n:

    Denition 5.3 (HalfArity over S (of degree n)).                    Given an algebraic signature
S   and n ∈ N, we call halfarity over S of degree n a                 functor

                                   α : S -RMnd → LRModn (S, Pre) .
which is preinverse to the forgetful functor.

    As before we restrict ourselves to a class of such functors. Again, we start with
the   tautological   module:

   Denition 5.4 (Tautological Module of Degree n). Given n ∈ N, any relative
monad    R over ∆T induces a monad Rn over ∆Tn with object map (V, t1 , . . . , tn ) 7→
(RV, t1 , . . . , tn ). To any relative S monad R we associate the tautological module
of Rn ,

                           Θn (R) := (Rn , Rn ) ∈ LRModn (S, PreTn ) .
Furthermore, we again use     canonical natural transformations (cf. Def. 3.41) to build
classic halfarities; these transformations specify context extension (derivation) and
selection of specic object types (bre):

                                                        Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
88       ·        B. Ahrens




     Denition 5.5       (Classic HalfArity).           As with monads (cf. Sect. 3.3), we restrict
our attention to          classic   halfarities, which we dene analogously to Def. 3.42 as
constructed using derivations and products, starting from the bres of the tauto-
logical module and the constant singleton module. We omit the precise statement
of this denition.

     A halfarity of degree     n thus associates, to any relative S monad P                    over a set of
types    T,   a   family of P modules indexed by T n :
     Remark 5.6        (Module of Higher Degree corresponds to a Family of Modules (II)).
Remark 3.37 applies analogously to modules over relative modules.                                   More pre-
cisely, let       T   be a set and let     R      be a monad on the functor          ∆T . Then a module
M     over the monad          Rn    corresponds precisely to a family of             Rmodules (Mt )t∈T n
by (un)currying.            Similarly, a morphism              α : M → N        of   modules of degree n
is equivalent to a family             (αt )t∈T n    of morphisms of modules of degree zero with
αt : Mt → Nt .
     An arity of degree       n ∈ N for terms over an algebraic signature S is dened to be a
pair of functors from relative        S monads to modules in LRModn (S, Pre). The degree
n    corresponds to the number of object type indices of its associated constructor.
As an example, the arities of             Abs      and   App   of Ex. 1.3 are of degree     2.
     Denition 5.7 (TermArity, Signature over S ).                   A   classic arity α over S of degree
n    is a pair
                                                                
                                              s = dom(α), cod(α)
of halfarities over        S   of degree     n   such that

dom(α) is classic and

cod(α) is of the form               [Θn ]τ   for some canonical natural transformation               τ   as in
     Def. 3.41.

Any classic arity is thus syntactically of the form given in Disp. (3.8). Note, however,
that the denition of  Θ in Sect. 3.3 diers from the one used in the present chapter.
We write dom(α) → cod(α) for the arity α, and dom(α, R) := dom(α)(R) and
similar for the codomain and morphisms of relative S monads. Given a weighted
set (J, d) as in Def. 3.44, a termsignature Σ over S indexed by (J, d) is a J -family
Σ of classic arities over S , the arity Σ(j) being of degree d(j) for any j ∈ J .
     Denition 5.8        (Typed Signature).             A   typed signature   is a pair   (S, Σ)   consisting
of an algebraic signature             S   for sorts and a termsignature             Σ   (indexed by some
weighted set) over         S.
     Example 5.9. Ex. 3.47 and 3.48 still apply. Note, however, that the underlying
denition of  Θ diers from that of Sec. 3, and that bre and derivation are adapted
accordingly.

5.2     Representations of 1Signatures
     Denition 5.10 (Representation of an Arity, a Signature over S ). A representa-
tion of an arity  α over S in an S monad R is a morphism of relative modules
                                          dom(α, R) → cod(α, R) .
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                         Initiality for Typed Syntax and Semantics        ·     89




A representation      R of a signature over S is a given by a relative S monad  called
R    as well  and a representation    αR of each arity α of S in R.
     Representations of   (S, Σ)   are the objects of a category       Rep∆ (S, Σ),   whose mor-
phisms are dened as follows:

     Denition 5.11 (Morphism of Representations). Given representations P and R
of a typed signature   (S, Σ), a morphism of representations f : P → R is given by
a    morphism of relative S monads f : P → R, such that for any arity α of Σ the
following diagram of module morphisms commutes:


                            dom(α, P )
                                               αP       / cod(α, P )

                             dom(α,f )                     cod(α,f )
                                                          
                            dom(α, R)                   / cod(α, R).
                                               αR

  Lemma 5.12: For any typed signature (S, Σ), the category of representations of
(S, Σ) has an initial object.
Proof.   The initial object is obtained, analogously to the untyped case (cf. Lem. 4.5,
4.20, 4.21), via an adjunction      ∆∗ a U∗   between the categories of representations of
(S, Σ)   in relative monads and those in monads as in Sect. 3.
     In more detail, to any relative S monad (T, P ) ∈ S -RMnd we associate the S 
monad    U (T, P ) := (T, U P ) where U∗ P is the monad obtained by postcomposing
with   the forgetful functor U
                                T
                                  : PreT → SetT . Substitution for U∗ P is dened, in
each   bre, as in Lem. 2.83. For any arity s ∈ Σ we have that

                              U∗ dom(s, P ) ∼
                                            = dom(s, U∗ P ) ,
and similar for the codomain. The postcomposed representation morphism     U∗ s(P )
hence represents   s in U∗ P in the sense of Sect. 3. This denes the functor U∗ :
Rep∆ (S, Σ) → Rep(S, Σ). Conversely, to any S monad we can associate a relative
S monad by postcomposing with ∆T : SetT → PreT , analogous to the untyped
                                                  ∆
case in Def. 4.15, yielding ∆∗ : Rep(S, Σ) → Rep (S, Σ). In summary, the natural
isomorphism

                  ϕR,P : Rep∆ (S, Σ) (∆∗ R, P ) ∼
                                                          
                                                = Rep(S, Σ) (R, U∗ P )
is given by postcomposition with the forgetful functor (from left to right) resp. the
functor   ∆   (from right to left).



5.3     Inequations
Analogously to the untyped case (cf. Defs. 4.22, 4.30), an inequation associates,
to any representation of   (S, Σ) in a relative monad P , two parallel morphisms
of P modules. However, similarly to arities, an inequation may now be, more
precisely, a family of inequations, indexed by object types. Consider the simply
typed lambda calculus, which was dened with typed abstraction and application.
Similarly, we have a typed substitution operation for TLC, which substitutes a term
of type s ∈ TTLC for a free variable of type s in a term of type t ∈ TTLC , yielding

                                               Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
90      ·      B. Ahrens




again a term of type        t.    For   s, t ∈ TTLC      and   M ∈ TLC(V ∗s )t           and   N ∈ TLC(V )s ,
beta reduction is specied by



                                     λs,t M (N ) ; M [∗ := N ] ,
where our notation hides the fact that not only abstraction, but also application
and substitution are typed operations. More formally, such a reduction rule might
read as a family of inequations between morphisms of modules

                                                                      s
                            apps,t ◦ (abss,t × id) ≤            _[∗       :=t   _]   ,
where    s, t ∈ TTLC   range over types of the simplytyped lambda calculus. Analo-
gously to Sect. 3.3, we want to specify the beta rule without referring to the set
TTLC , but instead express it for an arbitrary representation R of the typed signature
(STLC , ΣTLC ) (cf. Exs. 3.2, 3.47), as in


                                 appR ◦ (absR × id) ≤           _[∗    := _] ,
where both the left and the right side of the inequation are given by suitable                        R
module morphisms of degree 2. Source and target of a                          halfequation accordingly
are given by functors from representations of a typed                      signature (S, Σ) to a suitable
category of modules. A halfequation then is a natural transformation between its
source and target functor:

  Denition 5.13 (Category of HalfEquations). Let (S, Σ) be a signature. An
(S, Σ)module U of degree n ∈ N is a functor from the category of representations
of (S, Σ) as dened in Sect. 5.2 to the category LRModn (S, wPre) (cf. Def. 5.2)
commuting with the forgetful functor to the category of relative monads. We dene
a morphism of       (S, Σ)modules        to be a natural transformation which becomes the
identity when composed with the forgetful functor. We call these morphisms                              half
equations (of degree n). We write U R := U (R) for the                      image of the representation
R under the S module U , and similar for morphisms.
  Denition 5.14 (Substitution as HalfEquation). Given a relative monad on
∆T , its associated substitutionofonevariable operation (cf. Def. 2.111) yields a
family of module morphisms, indexed by pairs (s, t) ∈ T . By Rem. 5.6 this family
is equivalent to a module morphism of degree 2. The assignment

                         subst : R 7→ substR : [R̂2 ]12 × [R̂2 ]1 → [R̂2 ]2
thus yields a halfequation of degree                2    over any signature             S.   Its domain and
codomain are classic.

     Example 5.15    (Ex. 3.47 continued).            The map

            app ◦ (abs × id) : R 7→ app ◦ (absR × idR ) : [R̂2 ]12 × [R̂2 ]1 → [R̂2 ]2
                                                R


is a halfequation over the signature               TLC,   as well as over the signature of          PCF.
     Denition 5.16.       Any classic arity of degree          n,
                             s=     [Θn ]τσ11   × ... ×   [Θn ]τσm
                                                                 m
                                                                     → [Θn ]σ ,

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                           Initiality for Typed Syntax and Semantics           ·     91




denes a classic     S module
                            dom(s) : R 7→ [Rn ]τσ11 × . . . × [Rn ]τσm
                                                                     m
                                                                       .
  Denition 5.17 (Inequation). Given a signature (S, Σ), an inequation over (S, Σ),
or (S, Σ)inequation, of degree n ∈ N is a pair of parallel halfequations between
(S, Σ)modules of degree n. We write α ≤ γ for the inequation (α, γ). We leave
the degree implicit whenever possible, analogously to Rem. 3.33.

     Example 5.18    (Beta Reduction).       For any suitable 1signature  i.e. for any 1
signature that has an arity for abstraction and an arity for application  we specify
beta reduction through an inequation of degree               2   using the parallel halfequations
of Def. 5.14 and Ex. 5.15:

                      app ◦ (abs × id) ≤ subst : [Θ]12 × [Θ]1 → [Θ]2 .
     Example 5.19 (Fixpoints and Arithmetics of PCF).                The reduction rules for       PCF
are informally given in Fig. 7. We specify these reduction rules as inequations over
the 1signature of     PCF   (cf. Ex. 3.48) as follows:

                              app ◦ (abs × id) ≤ subst : [Θ]12 × [Θ]1 → [Θ]2
                                            Fix ≤ app ◦ (id, Fix) : [Θ]1⇒1 → [Θ]1
                              app ◦ (Succ, n) ≤ n + 1 : ∗ → [Θ]ι
                             app ◦ (Pred, 0) ≤ 0 : ∗ → [Θ]ι
            app ◦ (Pred, app ◦ (Succ, n)) ≤ n : ∗ → [Θ]ι
                             app ◦ (Zero?, 0) ≤ T : ∗ → [Θ]o
            app ◦ (Zero?, app ◦ (Succ, n)) ≤ F : ∗ → [Θ]o
                                                .
                                                .
                                                .

  Denition 5.20 (Representation of Inequations). A representation of an (S, Σ)
inequation α ≤ γ : U → V (of degree n) is any representation R over a set of
                              R
types T of (S, Σ) such that α   ≤ γ R pointwise, i.e. if for any pointed context
            T    n                          R
(X, t) ∈ Set × T , any t ∈ T and any y ∈ U(X,t) (t),

                                      αR (y) ≤ γ R (y) ,                                           (5.1)

where we omit the sort argument    t as well as the context (X, t) from α and γ . We
say that such a representation  R satises the inequation α ≤ γ .
  For a set A of (S, Σ)inequations, we call representation of ((S, Σ), A) any rep-
resentation of (S, Σ) that satises each inequation of A. We dene the category
of representations of the 2signature ((S, Σ), A) to be the full subcategory of the
category of representations of S whose objects are representations of ((S, Σ), A).
We also write (Σ, A) for ((S, Σ), A).
     According to Rem. 5.6, the inequation of Disp. (5.1) is equivalent to ask whether,
for any   t ∈ T n,   any   t∈T   and any   y ∈ UtR (X)(t),
                                      αtR (y) ≤ γtR (y) .



                                                    Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
92       ·      B. Ahrens




5.4     Initiality for 2Signatures
We are ready to state and prove an initiality result for typed signatures with in-
equations:

  Theorem 5.21: For any set of classic (S, Σ)inequations A, the category of
representations of ((S, Σ), A) has an initial object.
Proof.       The proof is analogous to that of the untyped case (c.f. Thm. 4.34). The
fact that we now consider             typed     syntax introduces a minor complication, on the
presentation of which we put the emphasis during the proof. The basic ingredients
for building the initial representation are given by the initial representation                      (Ŝ, Σ̂)
 or just       Σ̂   for short  in the category          Rep(S, Σ)      of representations in monads
on set families (cf. Thm. 3.53). Equivalently, the ingredients come from the initial
object    (Ŝ, ∆∗ Σ̂)    or just ∆∗ Σ̂ for short          of representations         without inequations
in the category         Rep∆ (S, Σ) (cf. Lem. 5.12).        We call      Σ̂   resp.   ∆∗ Σ̂ the monad resp.
relative monad underlying the initial representation
      The proof consists of 3 steps: at rst, we dene a preorder                      ≤A   on the terms of
Σ̂,   induced by the set        A   of inequations. Afterwards we show that the data of the
representation         Σ̂    substitution, representation morphisms etc.  is compatible
with the preorder  ≤A in a suitable sense. This will yield a representation Σ̂A of
(Σ, A). Finally we show that Σ̂A is the initial such representation.
 The monad underlying the initial representation:
                        Ŝ
For any context X ∈ Set and t ∈ Ŝ , we equip Σ̂X(t) with a preorder A by setting
 morally, cf. below , for x, y ∈ Σ̂X(t),



                       x ≤A y       :⇔        ∀R : Rep(Σ, A),     iR (x) ≤R iR (y) ,                  (5.2)

where        iR : ∆∗ Σ̂ → R         is the initial morphism of representations of                (S, Σ),   cf.
Lem. 5.12.           Note that the above denition in Disp. (5.2) is illtyped:                    we have
x ∈ Σ̂X(t),          which cannot be applied to (a bre of )                  iR (X) : ~g (Σ̂X) → R(~g X).
We denote by           ϕ = ϕR       the natural isomorphism induced by the adjunction of
Rem. 2.23 and Def. 2.22 obtained by retyping  along the initial morphism of
types    g : Ŝ → T = TR         towards the set    T of types of R,
                                                                           
                     ϕX,Y   : PreT ~g (Σ̂X), R(~g X) ∼= PreŜ Σ̂X, R(~g X) ◦ g .
Instead of the above denition in Disp. (5.2), we should really write

         x ≤A y        :⇔      ∀R : Rep(Σ, A),        (ϕ(iR,X )) (x) ≤R (ϕ(iR,X )) (y) ,              (5.3)

where we omit the subscript  R from                ϕ.   We have to show that the map

                                         X 7→ Σ̂A X := (Σ̂X, ≤A )
yields a relative monad on            ∆Ŝ .   The missing fact to prove is that the substitution
with a morphism

                                 f ∈ PreŜ (∆X, Σ̂A Y ) ∼
                                                        = SetŜ (X, Σ̂Y )
is compatible with the order             ≤A :   given any   f ∈ PreŜ (∆X, Σ̂A Y )        we show that


                                         σ Σ̂ (f ) ∈ SetŜ (Σ̂X, Σ̂Y )
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                           Initiality for Typed Syntax and Semantics                 ·     93




is monotone with respect to       ≤A      and hence (the carrier of ) a morphism


                              σ Σ̂A (f ) ∈ PreŜ (Σ̂A X, Σ̂A Y ) .
We overload the inx symbol           =    to denote monadic substitution. Note that this
notation now hides an implicit argument giving the sort of the term in which we
substitute. Suppose    x, y ∈ Σ̂X(t)       with       x ≤A y ,      we show

                                      x = f ≤A y = f .
Using the denition of    ≤A ,   we must show, for a given representation                   R   of   (Σ, A),
                       (ϕ(iR )) (x = f ) ≤R (ϕ(iR )) (y = f ) .                                        (5.4)

Let   g   be the initial morphism of types towards the types of                      R. Since i := iR       is
a morphism of representations  and thus in particular a                           monad morphism, it       is
compatible with the substitution of             Σ̂   and    R;    we have



                                                     ~
                                                     g (σ(f ))
                              ~g (Σ̂X)                               / ~g (Σ̂Y )                         (5.5)



                                 iX                                          iY


                                                                         
                              R(~g X)                               / R(~g Y ).
                                                σ R (iY ◦~
                                                         gf )

By applying the isomorphism           ϕ   on the diagram of Disp. (5.5), we obtain

                       ϕ(iY ) ◦ σ(f ) = ϕ (iY ◦ ~g (σ(f )))
                                          = ϕ (σ(iY ◦ ~g f ) ◦ iX )
                                          = g ∗ σ R (iY ◦ ~g f ) ◦ ϕ(iX ) .
                                                                
                                                                                                         (5.6)

Rewriting the equality of Disp. (5.6) twice in the goal Disp. (5.4) yields the goal

          g ∗ σ R (iY ◦ ~g f ) ((ϕ(iX ))(x)) = g ∗ σ R (iY ◦ ~g f ) ((ϕ(iX ))(y)) ,
                                                                   

                       ∗
                                           
which is true since g      σ R (iY ◦ ~g f ) is monotone and (ϕ(iX ))(x) ≤R (ϕ(iX ))(y)                     by
                                                                 Ŝ
hypothesis. We hence have dened a monad Σ̂A over ∆ .

  Lemma 5.22:        Lemma 4.35 generalizes to the typed setting of this chapter.
Proof of Lem. 5.22.    The proof is analogous to the proof of Lem. 4.35: we apply the
same reasoning in the corresponding bre.



 Representing Σ in Σ̂A :
                                                                       Σ̂
Any arity s ∈ Σ should be represented by the module morphism s , i.e. by the
representation of s in Σ̂. We have to show that those representations are compatible
with the preorder A. Given x ≤A y in dom(s, Σ̂)(X), we show (omitting the
                 Σ̂
argument X in s (X)(x))


                                      sΣ̂ (x)         ≤A         sΣ̂ (y) .
                                                        Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
94      ·       B. Ahrens




By denition, we have to show that, for any representation                          R with initial morphism
i = iR : Σ̂ → R     as before,

                                 ϕ(iX )(sΣ̂ (x))     ≤R      ϕ(iX )(sΣ̂ (y)) .
But these two sides are precisely the images of                       x   and   y    under the upperright
composition of the diagram of Def. 5.11 for the morphism of representations iR . By
rewriting with this diagram we obtain the goal
                                                                              
                  sR       dom(s)(iR ) (x)           ≤R      sR       dom(s)(iR ) (y) .

We know that       sR      is monotone, thus it is sucient to show
                                                                        
                             dom(s)(iR ) (x)         ≤R       dom(s)(iR ) (y) .
This goal follows from Lem. 5.22 (instantiated for the classic                        S module dom(s),       cf.
Def. 5.16) and the hypothesis             x ≤A y .   We hence have established a representation
 which we call Σ̂A              of   S in Σ̂A .
 Σ̂A satises A:
The next step is to show that the representation               Σ̂A satises A.         Given an inequation

                                                α≤γ:U →V
of A with a classic S module V , we must show that for any                          context   X ∈ SetŜ ,   any
t ∈ Ŝ and any x ∈ U (Σ̂A )(X)t in the domain of α we have
                                        αΣ̂A (x)     ≤A      γ Σ̂A (x) ,
where here and later we omit the context argument                      X   and the sort argument t. By
Lem. 5.22 the goal is equivalent to



               ∀R : Rep(Σ, A),           V (iR )(αΣ̂A (x))     ≤VXR         V (iR )(γ Σ̂A (x)) .            (5.7)

Let   R     be a representation of         (Σ, A).   We continue by proving Disp. (5.7) for                   R.
Remark 4.24 holds analogously in the typed setting of this chapter. The fact that
iR   is the carrier of a morphism of            (S, Σ)representations          from    ∆Σ̂    to   R   allows to
rewrite the goal as

                                αR U (iR )(x)                γ R U (iR )(x) ,
                                                                          
                                                     ≤VXR
which is true since         R   satises   A.
 Initiality of Σ̂A :
Given any representation      R of (Σ, A), the morphism iR is monotone with respect
to the orders on        Σ̂A    R by construction of ≤A . It is hence a morphism of
                                 and
representations from Σ̂A to R. Uniqueness of the morphisms iR follows from its
uniqueness in the category of representations of (S, Σ), i.e. without inequations.
Hence (Ŝ, Σ̂A ) is the initial object in the category of representations of ((S, Σ), A).



     Remark 5.23    (Iteration Principle by Initiality).                  The universal property of the
language generated by a 2signature yields an                 iteration principle         to dene maps 
translations  on this language, which are certied to be compatible with substi-
tution and reduction in the source and target languages. How does this iteration

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                            Initiality for Typed Syntax and Semantics                ·      95




principle work? More precisely, what data (and proof ) needs to be specied in order
to dene such a translation via initiality from a language, say,                                      (Ŝ, Σ̂A ) to another
language          (Ŝ 0 , Σ̂0A0 ),   generated by signatures              (S, Σ, A)    and   (S 0 , Σ0 , A0 ), respectively?
The translation is a morphism  an initial one  in the category of representa-
tions of the signature                   (S, Σ, A) of the source language. It is obtained by equipping
the relative monad                   Σ̂0A0 underlying the target language with a representation of the
signature         (S, Σ, A).         In more detail:

(1) we give a representation of the type signature                                 S   in the set   Ŝ 0 .   By initiality of
                                                                 0
      Ŝ ,   this yields a translation                 Ŝ → Ŝ       of sorts.

(2) Afterwards, we specify a representation of the term signature                                      Σ in the monad
      Σ̂0A0   by dening suitable (families) of morphisms of                                Σ̂0A0 modules. This yields
      a representation                R    of   (S, Σ)   in the monad        Σ̂0A0 .
By initiality, we obtain a morphism                          f : (Ŝ, Σ̂) → R of representations of (S, Σ), that
is, we obtain a translation from                           (Ŝ, Σ̂) to (Ŝ 0 , Σ̂0 ) as the colax monad morphism
underlying the morphism                         f.   However, we have not yet ensured that the translation
f    is compatible with the respective reduction preorders in the source and target
languages.

(3) Finally, we verify that the representation                               R of (S, Σ) satises the inequations
      of     A,    that is, we check whether, for each                       α ≤ γ : U → V ∈ A, and for each
      context         V,    each      t ∈ Ŝ    and    x ∈ UVR (t),
                                                           αR (x) ≤ γ R (x) .
After verifying that                  R    satises the inequations of                 A,   the representation       R   is in
fact a representation of                 (S, Σ, A). The               initial morphism        f   thus yields a faithful
translation from              (Ŝ, Σ̂A ) to (Ŝ 0 , Σ̂0A0 ).
     Example 5.24             (Translation from             PCF      to   ULC,   Exs. 3.54 and 5.19 cont.).           Recall
the translations from                  PCF       to the untyped lambda calculus of Ex. 3.54. We might
attempt to specify the same translations using the iteration operator obtained by
Thm. 5.21, where                     PCF   is equipped with the reduction relation generated by the
inequations of Ex. 5.19 and                          ULC   is equipped with beta reduction as in Ex. 4.32.
However, representing the xedpoint operator of                                   PCF   by the lambda term           Θ   fails,
for reasons explained at the end of Sect. 9.
     For the translation of                 PCF       to the lambda calculus mapping the xedpoint op-
erator of         PCF      to the Turing xedpoint combinator, we have formalized its spec-
ication via initiality in the proof assistant Coq [Coq10].                                     After constructing the
category of representations of                        PCF,    we equip the untyped lambda calculus with a
representations of               PCF,      representing the arity            Fix   by the Turing operator           Θ.   The
formalization is explained in Sect. 9. Note that the translation is given by a                                            Coq
function and hence executable.



6.    FORMALIZING CATEGORY THEORY IN COQ
In this chapter we describe our computer formalization of general concepts of cat-
egory theory as presented in Sect. 2.                                We start with a brief introduction to our



                                                                     Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
96      ·     B. Ahrens




favourite theorem prover      Coq [Coq10].     We then describe the challenges one encoun-
ters when one attempts to formalize algebraic structures in general, and category
theory in particular, in      Coq.    Finally we present our implementation of monads
and modules over monads as well as their relative counterparts. Throughout the
chapter we explain features of        Coq   when we rst encounter them.


6.1    About the Proof Assistant Coq
The proof assistant Coq [Coq10] is an implementation of the Calculus of Inductive
Constructions (CIC) which itself is a constructive type theory. Its objects are terms
built according to a grammar (see the Coq manual [The10] for the term forming
rules). Each valid term has its associated type which is itself a term and which
is automatically computed by Coq. In Coq a typing judgment is written t : T,
meaning that t is a term of type T . Typing judgments are for example 1 : Nat and
plus : Nat −> Nat −> Nat. Function application is simply denoted by a blank, i.e.
we write f x for f (x).
   The CIC also treats propositions as types via the CurryHoward isomorphism,
hence a proof of a proposition P is in fact a term of type P . Accordingly, a proof
of a proposition A ⇒ B is a function A → B , i.e. a term which associates a proof
of B to any proof of A. As an example, the function id : P → P is a proof of the
tautology P ⇒ P . In the proof assistant Coq a user hence proves a proposition P
by providing a term p of type P. Coq checks the validity of the proof p by checking
whether p : P.
   Coq comes with extensive support to interactively build the proof terms of a given
proposition. In proof mode so-called tactics help the users to reduce the proposition
they want to prove  the goal  into one or more simpler subgoals, until reaching
trivial subgoals which can be solved directly.
     Particular concepts of     Coq   such as records and type classes, setoids, implicit
arguments and coercions are explained in a callbyneed fashion in the course
of the thesis.      One important feature is the        Section   mechanism (cf. also the        Coq
manual [The10]). Parameters and hypotheses declared in a section automatically
get discharged when closing the section.               Constants of the section then become
functions, depending on an argument of the type of the parameter they mentioned.
We illustrate this concept by means of a small example; consider the following                   Coq
declarations:

Section def_double.
Variable n : nat.
Denition double : nat := 2 ∗ n.
Check double.
 double
       : nat
Print Assumptions double.
 Section Variables:
 n : nat
Inside the section     def_double,    the constant      double   is of type   nat,   as we verify us-
ing the     Check   command. Furthermore, it depends on the section variable                  n : nat

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                         Initiality for Typed Syntax and Semantics        ·     97




declared using the      Variable   vernacular command.       After closing the section, the
constant    double   is a closed term of function type:

End def_double.
Check double.
 double
      : nat −> nat
Print Assumptions double.
 Closed under the global context
Eval compute in double 4.
      = 8 : nat
In our formalization, we use the       Section   mechanism extensively. When presenting
a denition depending on section variables, we either give a slightly modied, fully
discharged version of the statement  compared to the actual                  Coq   code , or
mention the section variables informally in the text.


6.2    Formalizing Algebraic Structures
An algebraic structure typically is given by some data  i.e. sets and operations
on them  that satises given properties.            For instance, a group is given by a
set, together with a binary associative multiplication and a unit element, such that
any element of the set has a multiplicative inverse. Such algebraic structures are
dened in a       hierarchic   way: for instance, any   group   is a particular    monoid     that
admits inverses. Thus any group is a monoid. The other way round, given a group,
if multiplication is commutative, then this group is actually abelian, and the group
is an element of the class of abelian groups.
     This hierarchic structure poses a major problem in the formalization of classic
mathematics, and the question of how to formalize algebraic structures is a subject
of active research. Put simply, the main question is how tightly one should pack
together the data and properties of an algebraic structure. If data and properties
are packed together tightly, then operations and properties can easily be associated
to their respective underlying sets, and this allows for overloading notation and
coercions. On the other hand, this tight packing makes it dicult to add data
and properties to an instance of an algebraic structure, e.g., to consider a group,
for which one has proved commutativity of multiplication, as an abelian group.
We do not attempt to propose a solution to the challenge of how to formalize
algebraic structures. However, we need to choose from the existing solutions. In
Coq    there are basically two possible answers:     records,   employed e.g., by Garillot et
al. [GGMR09], correspond to a tight packing of algebraic structure, whereas                   type
classes    [SO08], as used by Spitters and v. d. Weegen [SvdW11], correspond to a
rather loose packaging.
     Coq   records are implemented as an inductive data type with one constructor,
However, use of the vernacular command           Record   (instead of plain   Inductive)   allows
the optional automatic denition of the projection functions to the constructor ar-
guments  the elds of the record. Additionally, one can declare those projections
as   coercions,   i.e. they can be inserted automatically by      Coq, and left out in print-
ing. As an example for a coercion, it allows us to write           c : C for an object c of a
category     C.   Here the projection from the category type to the type of objects of

                                               Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
98      ·    B. Ahrens




a category is declared as a coercion (cf. Code 6.1). This is the formal counterpart
to the convention introduced in the informal denition of categories in Def. 2.1.
Another example of coercion is given in the denition of monad (cf. Def. 2.33),
where it corresponds precisely to the therementioned                  abuse of notation.    Finally,
an example of coercion that is        not   given by a projection is given by the tautological
module, i.e. the map that associates to any monad                  P   the tautological   P module
(cf. Def. 2.48).
     Type classes are implemented as records.              Similarly to the dierence between
records and inductive types, type classes are distinguished from records only in
that some metatheoretic features are automatically enabled when declaring an
algebraic structure as a class rather than a record. For details we refer to Sozeau's
article about the implementation of type classes [SO08] and Spitters and v. d.
Weegen's work [SvdW11].           Type classes dier from records in their usage, more
specically, in which data one declares as a             parameter     of the structure and which
one declares as a    eld.   The following example, borrowed from [SvdW11], illustrates
the dierent uses; we give two denitions of the algebraic structure of reexive
relation, one in terms of classes and one in terms of records:

Class Reexive {A : Type}{R : relation A} :=
   reexive : forall a, R a a.

Record Reexive := {
  carrier : Type ;
  car_rel : relation carrier ;
  rel_re : forall a, car_rel a a }.
Our main interest in classes comes from the fact that by using classes many of the
arguments of projections are automatically declared as                  implicit arguments. This
leads to more readable code since arguments that can be deduced by                    Coq do not
have to be written down. Thus it corresponds precisely to the mathematical practice
of not mentioning arguments (e.g. indices) which are clear from the context. An
instance of this behaviour can be seen in the denition of category in Def. 2.1,
where we omit the 3 object arguments  written as an index  of the dependent
composition of morphisms. In particular, the structure argument of the projection,
that is, the argument specifying the instance whose eld we want to access, is
implicit and deduced automatically by             Coq.   This mechanism allows for       overloading,
a prime example being the implementation of setoids (cf. Sect. 6.3.3) as a type class;
in a term  a   == b    denoting setoidal equality,        Coq   automatically nds the correct
setoid instance from the type of        a   and   b5 .
     We decide to dene our algebraic structures in terms of type classes rst, and
bundle the class together with some of the class parameters in a record afterwards,
as is shown in the following example for the type class                 Cat_struct   (cf. Code 6.3)
and the bundling record        Cat.

5 Beware! In case several instances of setoid have been declared on one and the same        Coq   type,
the instance chosen by Coq might not be the one intended by the user. This is the main reason
for Spitters and v. d. Weegen to restrict the elds of type classes to   propositions.


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                       Initiality for Typed Syntax and Semantics        ·     99




  Code 6.1.    (Bundling a type class into a record):

  Record Cat := {
       obj:> Type ;
       mor: obj −> obj −> Type ;
       cat_struct:> Cat_struct mor }.
This duplication of   Coq   denitions is a burden rather than a feature. We still pro-
ceed like this for the following reasons: in our case the use of records is unavoidable
since we want to have a     Coq type   of categories, of functors between two given cat-
egories, etc. This is necessary when those objects  functors, for instance  shall
themselves be the objects or morphisms of some category, as is clear from Code 6.1.
However, we prot from aforementioned features of type classes, notably automatic
declaration of some arguments as       implicit   and the resulting overloading.
  Apart from that, we do not employ any feature that makes the use of type classes
comfortable  such as maximally inserted arguments, operational classes, etc. 
since we usually work with the bundled versions. Readers who are interested in how
to use type classes in   Coq   properly, are advised to take a look at Spitters and v.
d. Weegen's paper [SvdW11]. There, the authors employ the mentioned bundling
of type classes in records only when necessary, e.g., when the considered structures
are to be the objects or morphisms of some category.


6.3   Formalizing Categories
As seen in Sect. 2.1, there are two denitions of category (Def. 2.1, Rem. 2.3), which
are equivalent from the point of view of a mathematician.              When implementing
category theory in dependent type theory, however, one needs to choose the one or
the other denition. This section explains how we implement categories in             Coq and
some consequences of our design choice.

  6.3.1   Which Denition to Formalize  Dependent HomSets?.                  The main dif-
ference concerning formalization between these two denitions is that of   compos-
ability of morphisms. The rst denition can be implemented directly only in type
theories featuring dependent types, such as the Calculus of Inductive Constructions
(CIC). The ambient type system, i.e. the prover, then takes care of composability
 terms with compositions of noncomposable morphisms are rejected as illtyped
terms.
  The second denition can be implemented also in provers with a simpler type
system such as the family of HOL theorem provers. However, since those (as well as
the CIC) are theories where functions are total, one is left with the question of how
to implement composition.       Composition might then be implemented either as a
functional relation or as a total function about which nothing is known (deducible)
on noncomposable morphisms. The second possibility is implemented in O'Keefe's
library [O'K04]. There the author also gives an overview of available formalizations
in dierent theorem provers with particular attention to the choice of the denition
of category.
  In our favourite prover   Coq, both denitions have been employed in signicant de-
velopments: the second denition is used in Simpson's construction of the Gabriel
Zisman localization [Sim06], whereas Huet and Saïbi's            ConCaT     [HS98] uses type


                                             Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
100       ·       B. Ahrens




families of morphisms as in Def. 2.1.                  To our knowledge there is no library in a
prover with dependent types such as               Coq or NuPrl [CAA+ 86] which develops and
compares both denitions with respect to provability, readability, and other criteria.
  We decided to construct our library using type families of morphisms.                                       In this
way the proof of composability of two morphisms is done by                         Coq type computation
automatically. As a consequence, we are sometimes obliged to insert trivial isomor-
phisms between equal  but not convertible  objects of some category, in order
to make compositions typecheck. For an example see Sect. 7.1.2.
  Coq's implicit argument            mechanism allows us to omit the deducible arguments, as
we do in Def. 2.1 for the object arguments                    c, d and e of the composition.              Together
with the possibility to dene inx notations, this brings our formal syntax close to
informal mathematical syntax.

  6.3.2        Setoidal Equality on Morphisms.              All the properties of a category                  C   con-
cern equality of two parallel morphisms, i.e.                        morphisms with same source and
target. In      Coq there is a polymorphic equality, called Leibniz equality, readily avail-
able for any type. However, this equality actually denotes       syntactic equality, which
already in the case of maps does not coincide with the mathematical equality on
maps  given by pointwise equality  that we would rather consider. With the use
of axioms  for the mentioned example of maps the axiom                           functional_extensionality
from the       Coq   standard library  one can often deduce Leibniz equality from the
mathematical equality in question. But this easily gets cumbersome, in particular
when the morphisms  as will be in our case  are sophisticated algebraic struc-
tures composed of a lot of data and properties. Instead, we require any collection
of morphisms         C(c, d)   for objects   c   and   d   of   C   to be equipped with an equivalence
relation, which plays the rôle of equality on this collection. In the                            Coq        standard
library equivalence relations are implemented as a type class with the underlying
type as a parameter        A, and the relation as well as a proof of it being an equivalence
as elds:

  Code 6.2.       (Setoid Type Class):

Class Setoid A := {
  equiv : relation A ;
  setoid_equiv :> Equivalence equiv }.
Setoids as morphisms of a category have been used by Aczel [Acz93] in LEGO (there
a setoid is simply called set) and Huet and Saïbi (HS) [HS98] in                         Coq.          HS's setoids
are implemented as records of which the underlying type is a component instead of
a parameter. This choice makes it necessary to duplicate the denitions of setoids
                                                                                                 6
and categories in order to make them available with a higher type                                  .

  6.3.3        Coq Setoids and Setoid Morphisms.                    Setoids in   Coq   are implemented as a
type class (cf. Code 6.2) with a type parameter                        A   and a relation on       A as well as
a proof of this relation being an equivalence as elds. For the term                              equiv a b the

6 In HS's     ConCaT, a type     T   that is dened after the type of setoids cannot be the carrier of a
setoid itself. As a remedy, HS dene a type Setoid' isomorphic to Setoid               after   the denition of T.
The type of Setoid' now being higher than that of T, one can dene a term of type Setoid' whose
carrier is T.


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                             Initiality for Typed Syntax and Semantics               ·        101




inx notation  a        == b    is introduced. The instance argument of                equiv     is implicit
(cf. Sect. 6.2).
  A    morphism of setoids          between setoids     A   and   B   is a   Coq   function on the under-
lying types which is compatible with the setoid relations on the source and target.
That is, it maps equivalent terms of            A to equivalent terms of B, or, in mathematical
notation,

                                 a ≡A a0     implies     f (a) ≡B f (a0 ) .                               (6.1)

In the     Coq   standard library such morphisms are implemented as a type class

Class Proper {A} (R : relation A) (m : A) : Prop :=
  proper_prf : R m m.
where the type         A   is instantiated with a function type              A −> B   and the relation         R
on    A −> B      is instantiated with pointwise compatibility :
                                                                             7



Denition respectful (A B : Type) (R : relation A) (R' : relation B) :=
 fun f g => forall x y, R x y −> R' (f x) (g y).
Notation " R ==> R' " := (@respectful _ _ (R%signature) (R'%signature))
   (right associativity, at level 55) : signature_scope.
Given      Coq types A and B equipped with relations R : relation A and R' : relation B,
respectively, and a map    f : A −> B, the statement Proper (R ==> R')f  replacing
aforementioned notation  really means

Proper (respectful R R') f ,
which is the same as           respectful R R' f f,   which itself just means

forall x y, R x y −> R' (f x) (f y) .
This is indeed the statement of Disp. (6.1) in the special case that                         R     and   R'   are
equivalence       relations.
  For any component of an algebraic structure that is a map dened on setoids,
we add a condition of the form              Proper...   in the formalization.          Examples are the
categorical composition (Code 6.3) and the monadic substitution map (Code 6.10).
Rewriting related terms under those equivalence relations is tightly integrated in
the   rewrite    tactic of   Coq.
  6.3.4      Coq Implementation of Categories.              As a result of the aforementioned con-
siderations, we adopt Sozeau's denition of category [SO08], which itself is a variant
of the denition given by Huet and Saïbi [HS98]. Unlike Huet and Saïbi's contribu-
tion   ConCaT,      Sozeau's approach uses        type classes    for algebraic structures and thus
avoids the universe inconsistencies that have to be circumvented by duplicating
denitions in       ConCaT      (cf. Sect. 6.3.2). More precisely, in Sozeau's implementation
of setoids (cf. Code 6.2), the carrier type is a            parameter        instead of a   eld   as in Huet
and Saïbi's. Our type class of categories is parametrized by a type of objects and


7 In the   Coq   standard library the denition of respectful is actually a special case of a more general
denition of a heterogeneous relation respectful_hetero.




                                                      Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
102       ·     B. Ahrens




a type family of morphisms, whose parameters are the source and target objects.

  Code 6.3.     (Type Class of Categories):

Class Cat_struct (obj : Type)(mor : obj −> obj −> Type) := {
  mor_oid :> forall a b, Setoid (mor a b) ;
  id : forall a, mor a a ;
  comp : forall {a b c}, mor a b −> mor b c −> mor a c ;
  comp_oid :> forall a b c, Proper (equiv ==> equiv ==> equiv) (@comp a b c) ;
  id_r : forall a b (f: mor a b), comp f (id b) == f ;
  id_l : forall a b (f: mor a b), comp (id a) f == f ;
  assoc : forall a b c d (f: mor a b) (g:mor b c) (h: mor c d),
       comp (comp f g) h == comp f (comp g h) }.
Compared to Def. 2.1 there are two additional elds: the eld

mor_oid :> forall a b, Setoid (mor a b)
equips each collection of morphisms    mor a b with a custom equivalence relation.
The eld  comp_oid states that the composition comp of the category is compatible
with the setoidal structure on the morphisms given by the eld mor_oid as explained
in Sect. 6.3.3. We recall that setoidal equality is overloaded and denoted by the
inx symbol `=='. In the following we write `a             −−−> b' for mor a b        and   f;;g   for
the composition of morphisms          f : a −−−> b     and  g : b −−−> c 8 .
  6.3.5     The Categories of Interest. The category Set is formalized in Coq as the
category of   Coq types. By using Coq types and functions as objects and morphisms
of this   category, we obtain executable Coq substitution and translation maps, cf.
Code 9.11.

  Code 6.4. (Set,     Def. 2.4):

Program Instance TYPE_struct : Cat_struct (fun a b => a −> b) := {
   mor_oid a b := TYPE_hom_oid a b ;
   id a := fun x : a => x ;
   comp a b c := fun (f : a −> b) (g : b −> c) => fun x => g (f x) }.
In this instance declaration, the elds      id_r, id_l and assoc are lled automatically by
the   Program   framework, cf. Sect. 6.3.7. For a set     T , the category SetT of Def. 2.20
has, as objects,    Coq     type families   indexed by T . Morphisms between two such
objects are suitable families of      Coq   functions :

  Code 6.5.     (Category of Type Families):

Program Instance ITYPE_struct : Cat_struct (obj := T −> Type)
          (fun A B => forall t, A t −> B t) := {
  mor_oid := INDEXED_TYPE_oid ; (* pointwise equal. in each component *)
  comp A B C f g := fun t => fun x => g t (f t x) ;
  id A := fun t x => x }.

8 Coq deduces and inserts the missing object arguments   a, b   and c of the composition automat-
ically from the type of the morphisms. For this reason those arguments are called      implicit    (cf.
Sect. 6.2).


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                           Initiality for Typed Syntax and Semantics              ·      103




We also employ categories whose objects are families of                        preordered   sets (i.e.   Coq
types), and morphisms are monotone                Coq     functions. We omit their denition.

  6.3.6    Initial Objects.       Initial objects have been dened in Def. 2.5.                 Formally,
we implement the initiality structure as a type class, parametrized by categories.
Its elds are given by an object Init of the category, a map InitMor mapping each
object a of the category to a morphism from Init to a and a proposition stating that
InitMor a is unique for any object a.
Class Initial (C : Cat) := {
  Init : C ;
  InitMor: forall a : C, Init −−−> a ;
  InitMorUnique: forall a (f : Init −−−> a), f == InitMor a }.
Note that the initial morphism is                not   given by an existential statement of the
form   ∀a, ∃f : . . .,   or, inCoq    terms, using an        exists   statement. This is because the
Coq    existential lies in    Prop   and hence does not allow for elimination  witness
extraction  when building anything but proofs.

  6.3.7    Interlude on the Program feature.              The   Program Instance vernacular allows
to ll in elds of an instance of a type class by means of tactics.                         Indeed, when
omitting a eld in an instance declaration  such as the proofs of associativity                      assoc
and left and right identity         id_l   and   id_r    in Code 6.4.  the        Program     framework
creates an     obligation   for each missing eld, making use of the information that the
user provided for the other elds. As an example, the obligation created for the
eld   assoc   of the previous example is to prove associativity for the composition
dened by

comp f g := fun x => g (f x) .
It then tries to solve the resulting obligations using the tactic that the user has
specied via the         Obligation Tactic   command. In case the automatic resolution of
the obligation fails, the user can enter the interactive proof mode nish the proof
manually.
  It is technically possible to ll in both              data   and    proof   elds automatically via
the   Program framework.          However, in order to avoid the automatic inference of data
which we cannot control, we always specify                   data directly      as is done in Code 6.4,
and rely on automation via           Program     only for    proofs.
  6.3.8    Retyping and Option.            We present the formalization of some commonly
used denitions. The reader might want to skip this section and come back to it
when being pointed back here.
  We dene retyping (cf. Rem. 2.23) for families of sets and preordered sets through
an inductive type:

  Code 6.6.      (Retyping Functor, Rem. 2.23):

Variables (T T' : Type) (g : T −> T').
Inductive retype (V : ITYPE T) : ITYPE T' :=
  | ctype : forall t, V t −> retype V (g t).


                                                       Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
104      ·     B. Ahrens




  The constructor      ctype : forall V t, V t −> retype V (g t)         is the carrier of the nat-
ural transformation of the same name of Rem. 2.23. Given a family                 V    of   preordered
sets, the preorder on      ~g V   is induced by the preorder on     V:
Inductive retype_ord (V : IPO T) : forall u, relation (retype g V (u)) :=
  | ctype_ord : forall t (x y : V t), x <<< y −> retype_ord (ctype g x) (ctype g y).
The option data type is implemented in the module                      Coq.Init.Datatypes         of the
Coq   standard library.

  Code 6.7.     (Option,  2.2.3.1):

Inductive option (A:Type) : Type :=
  | Some : A −> option A
  | None : option A.
We can turn the map         A 7→ A0 := A + {∗}         into a monad as follows:

  Code 6.8.     (Option Monad):

Program Instance option_monad_s :
  Monad_struct (C:=TYPE) (option) := {
  weta := @Some ;
  kleisli a b f := fun t => match t with
                      | Some y => f y
                      | None => None
                      end }.
There is also a typed variant of the option data type:

  Code 6.9.     (Typed Option,  2.2.3.1):

Inductive opt (u : T) (V : ITYPE T) : ITYPE T :=
  | some : forall t : T, V t −> opt u V t
  | none : opt u V u.
Given a list   l over T, the multiple addition of variables with (object language) types
according to     l to a set of variables V is dened by recursion over l. For this enriched
         variables we introduce the notation V        l.
                                                   ∗∗
set of

Fixpoint pow (l : [T]) (V : ITYPE T) : ITYPE T :=
  match l with
  | nil => V
  | b::bs => pow bs (opt b V)
  end.
The map      opt is functorial, as is the multiple addition of variables pow. On mor-
phisms the    pow operation is dened by recursively applying the functoriality of opt,
where for the latter we use a special notation with a prexed hat.

Fixpoint pow_map (l : [T]) V W (f : V −−−> W) : V                 ∗∗
                                                                       l −−−> W       ∗∗
                                                                                           l :=
  match l return V ∗∗ l −−−> W ∗∗ l with
  | nil => f
  | b::bs => pow_map (^f)
  end.

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                       Initiality for Typed Syntax and Semantics          ·     105




6.4   Monads, Modules and their Morphisms
Implementing monads leaves one with the choice between the denitions given in
Def. 2.33 and Def. 2.65. The rst denition, while preferred by category theorists,
has the inconvenience that dening instances of monads such as monadic syntax
would require proving commutativity of the square, e.g., using multiple induction
for monadic syntax. Furthermore the second denition is wellknown in the pro-
gramming community for its use in Haskell. We thus decide to implement the
denition of Def. 2.65.     Since we are mainly interested in its instances over the
category of (families of ) sets, we can dene convenient inx notation for its substi-
tution.
    Formally, a monad (cf. Def. 2.65) is a type class parametrized by a category                  C
and a function     F : C −> C   on the objects of     C:
    Code 6.10.   (Monad, Def. 2.65):

Class Monad_struct (C : Cat) (F : C −> C) := {
  weta : forall c, c −−−> (F c);
  kleisli : forall a b, (a −−−> F b) −> (F a −−−> F b);
  kleisli_oid :> forall a b, Proper (equiv ==> equiv) (kleisli (a:=a) (b:=b));
  eta_kl : forall a b (f : a −−−> F b), weta a ;; kleisli f == f;
  kl_eta : forall a, kleisli (weta a) == id _;
  dist : forall a b c (f : a −−−> F b) (g : b −−−> F c),
       kleisli f ;; kleisli g == kleisli (f ;; kleisli g) }.
Monads admit a functorial structure:

    Code 6.11.   (Functoriality for Monads, Rem. 2.66):

Variable T : Monad C.
Denition lift : forall a b (f: a −−−> b), T a −−−> T b :=
        fun a b f => kleisli (f ;; weta b).
We present two dierent implementations of monad morphisms. The more general
denition implements colax monad morphisms as dened in Def. 2.69:

    Code 6.12.   (Colax Monad Morphism, Def. 2.69):

Class colax_Monad_Hom_struct (Tau : forall c, F (P c) −−−> Q (F c)) := {
  gen_monad_hom_kl : forall c d (f : c −−−> P d),
       #F (kleisli f) ;; Tau _ ==
           Tau _ ;; (kleisli (#F f ;; Tau _ )) ;
  gen_monad_hom_weta : forall c : C,
       #F (weta c) ;; Tau _ == weta _ }.
When working exclusively with a special case of a more general denition, it is more
convenient to implement this special case as a separate denition: for two monads
P   and   Q   over the same category   C,   a   simple morphism of monads           as used in
Sect. 3.2  is given by a family of morphisms           τc ∈ C(P c, Qc) that       is compatible
with the monadic structure:




                                                Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
106        ·        B. Ahrens




    Code 6.13.       (Simple Monad Morphism, Def. 3.12):

    Class Monad_Hom_struct (Tau: forall c, P c −−−> Q c) := {
      monad_hom_kl: forall c d (f: c −−−> P d),
          kleisli f ;; Tau d == Tau c ;; kleisli (f ;; Tau d) ;
      monad_hom_weta: forall c: C, weta c ;; Tau c == weta c }.
It follows from these commutativity properties that the family                   τ is a natural trans-
formation between the functors induced by the monads                    P   and   Q. Given a monad
P   over   C,   a   P module        with codomain   D   is formalized as follows:

    Code 6.14.       (Module, Def. 2.71):

Variable P : Monad C.
Class Module_struct (M : C −> D) := {
  mkleisli: forall c d, (c −−−> P d) −> (M c −−−> M d);
  mkleisli_oid :> forall c d, Proper (equiv ==> equiv) (mkleisli (c:=c)(d:=d));
  mkl_weta: forall c, mkleisli (weta c) == id _ ;
  mkl_mkl: forall c d e (f : c −−−> P d) (g : d −−−> P e),
      mkleisli f ;; mkleisli g == mkleisli (f ;; kleisli g) }.
For two modules             S   and   T   with codomain   D   over a monad   P    as above, a module
morphism from           S   to   T    is given by a family of maps, indexed by the objects of      C,
commuting with module substitution:

    Code 6.15.       (Module Morphism, Def. 2.73):

Class Module_Hom_struct (N: forall x, S x −−−> T x) := {
  mod_hom_mkl: forall c d (f: c −−−> P d),
        mkleisli f ;; N _ == N _ ;; mkleisli f }.

6.5   Relative Monads, Formalized
As opposed to (plain) monads, we have only one denition of relative monads
available. The implementation of this denition in                Coq is similar to that of monads
(cf. Code 6.10). Given a functor               F : C → D,     a relative monad is given by a map
T :C→D          on the objects of the categories involved, and data analogous to that of
a monad:

    Code 6.16.       (Relative Monad, Def. 2.75):

Variables C D : Cat.
Variable F : Functor C D.
Class RMonad_struct (T : C −> D) := {
  rweta: forall c : C, F c −−−> T c ;
  rkleisli: forall a b : C, F a −−−> T b −> T a −−−> T b ;
  rkleisli_oid:> forall a b, Proper (equiv ==> equiv) (rkleisli (a:=a) (b:=b)) ;
  reta_kl : forall a b: obC, forall f : F a −−−> T b, rweta a ;; rkleisli f == f ;
  rkl_eta : forall a, rkleisli (rweta a) == id _ ;
  rdist: forall a b c (f : F a −−−> T b) (g : F b −−−> T c),
              rkleisli f ;; rkleisli g == rkleisli (f ;; rkleisli g) }.
Analogously to monads we dene functoriality for a given relative monad                      P:
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                          Initiality for Typed Syntax and Semantics         ·     107




     Code 6.17.   (Functoriality for Relative Monads, Rem. 2.80):

Variable P : RMonad C.
Denition rlift : forall a b (f : a −−−> b), P a −−−> P b :=
        fun a b f => rkleisli (#F f ;; rweta b).
In the following we consider morphisms of relative monads in varying generality: one
denition (Def. 4.3) is analogous to the simple morphisms of monads (cf. Code 6.13),
another implements the colax version of Def. 2.87. For the statement of the second,
general, denition, we place ourselves in the environment given in Def. 2.87.                      In
short, we have a natural transformation           N : F 0 G ⇒ G0 F : C → D0 .
     Code 6.18.   (Colax Morphism of Relative Monads, Def. 2.87):

Variable N : NT (CompF G F') (CompF F G').
Class colax_RMonad_Hom_struct (tau: forall c : C, G' (P c) −−−> Q (G c)):={
  gen_rmonad_hom_rweta : forall c : C,
    N _ ;; #G' (rweta c) ;; tau c == rweta (G c) ;
  gen_rmonad_hom_rkl : forall (c d : C) (f : F c −−−> P d),
    #G' (rkleisli f) ;; tau d == tau c ;; rkleisli (a:=G c) (N c ;; #G' f ;; tau _ ) }.
A    module M     over a relative monad      P   (on a functor   F)   is given by data similar to
that of a module over a monad, except for the insertion of applications of                 F    where
necessary.

     Code 6.19.   (Module over a Relative Monad, Def. 2.90):

Class RModule_struct (M : C −> E) := {
  rmkleisli: forall c d (f : F c −−−> P d), M c −−−> M d ;
  rmkleisli_oid :> forall c d, Proper (equiv ==> equiv) (rmkleisli (c:=c)(d:=d)) ;
  rmkl_rweta: forall c : C, rmkleisli (rweta c) == id (M c) ;
  rmkl_rmkl: forall c d e (f : F c −−−> P d) (g : F d −−−> P e),
          rmkleisli f ;; rmkleisli g == rmkleisli (f ;; rkleisli g) }.
Given two modules       M    and   N   with codomain    D   over a relative monad   P , a module
morphism from       M   to   N     is given by a collection of maps        (Sc : M c → N c)c∈C
commuting with module substitution:

     Code 6.20.   (Morphism of Relative Modules, Def. 2.94):

Variables M N : RModule P D.
Class RModule_Hom_struct (S : forall c : C, M c −−−> N c) := {
  rmod_hom_rmkl: forall c d (f : F c −−−> P d),
         rmkleisli f ;; S d == S c ;; rmkleisli f }.

7.    FORMALIZATION OF ZSIDÓ'S THEOREM
In this chapter we describe the formalization in the proof assistant               Coq   [Coq10] of
Zsidó's initiality theorem presented in Sect. 3.2. In particular, we explain what we
omitted in the informal presentation  the construction of the initial representation
of a given simplytyped signature.




                                                  Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
108       ·     B. Ahrens




7.1      Signatures & Representations
An  arity determines the type and binding behaviour of a constructor, and a signa-
ture is a family of arities. A representation of a signature S is given by a monad
P (over a suitable category) and a morphism of P modules for each arity α of S ,
where the source and target module of this morphism are determined by α. Among
those representations the object of interest is the initial one, i.e. the representa-
tion from which there exists exactly one morphism of representations to any other
representation. The initial representation is called syntax generated by S .

  7.1.1   Using Lists for Algebraic Arities & Signatures. For the formal denitions
let us x a set T of object language types. As explained in Def. 3.20, an algebraic
arity over T is determined by a pair of a list of data and an element t0 ∈ T , yielding
an ecient and concise way to specify algebraic arities. An algebraic signature could
thus be implemented  as in Def. 3.9  as a pair consisting of a type        sig_index
 which is used for indexing the arities  and a map from the indexing type to
the actual arity type, which is simply built using lists  for which we employ a
Haskelllike notation  and products:

  Code 7.1.     (Signature, Def. 3.9):

Notation "[ T ]" := (list T) (at level 5).
Record Signature : Type := {
  sig_index : Type;
  sig : sig_index −> [[T] ∗ T] ∗ T }.
However, a slight modication turns out to be useful. During the construction of the
initial representation, a universal quantication over arities of a signature   S   with a
given target type     t∈T     is needed. Using the above hypothetical implementation,
this quantication could be achieved by using a sigma type:

Denition Signature_t (t : T) : Type := {s : sig_index S | snd (sig s) = t}.
This denition would be awkward to use since we would be obliged to handle
equality proofs when talking about indices, i.e. terms of sig_index S, with a specic
output type.      We can in fact do better: while the propositional equality as used
above would need our intervention, denitional equality  conversion  is handled
by Coq. Hence we decide to implement a signature over a set of types T as a function
that maps each t : T to the collection of arities whose output type is the given t. In
other words, the parameter t of Signature_t in the denition of signature replaces
the second component of the arities:

  Code 7.2.     (Signature, Def. 3.9):

Record Signature_t (t : T) : Type := {
  sig_index : Type ;
  sig : sig_index −> [[T] ∗ T] }.
Denition Signature := forall t, Signature_t t.
We discuss the formalization of the example signature of the simplytyped lambda
calculus (cf. Ex. 3.23). At rst we dene an indexing type       TLC_index_t    for each
t : T.    After that, we build an indexed signature    TLC_sig   mapping each index to
its arity:

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                          Initiality for Typed Syntax and Semantics        ·     109




  Code 7.3.    (Signature of          TLC,            Ex. 3.23):

Inductive TLC_index : T −> Type :=
   | TLC_abs : forall s t : T, TLC_index (s ∼> t)
   | TLC_app : forall s t : T, TLC_index t.

Denition TLC_arguments : forall t, TLC_index t −> [[T] ∗ T] :=
   fun t' r => match r with
      | TLC_abs s t => (s::nil,t)::nil
      | TLC_app s t => (nil,s ∼> t)::(nil,s)::nil
      end.
Denition TLC_sig t := Build_Signature_t t (@TLC_arguments t).

  7.1.2    Modules and Morphisms for Arities.                               To any signature given as a depen-
dent function of type Signature as in Code 7.2                   actual signature in
                                                                            we associate the
the sense of Def. 3.18. More precisely, for an arity s = [(s1 , t1 ), . . . , (sn , tn )], t0
given by lists we dene the functors dom(s) and cod(s), each of which, given a
                     T
monad P ∈ Mon(Set ) (cf. Def. 3.13), yield a P module with codomain Set. Note
that the bold face letters si denote lists of sorts.
   It would in principle be possible to build the module dom(s, P ) associated to a
monad P using the categorytheoretic machinery dened in Sects. 2.2.2 and 2.2.3,
i.e. by applying iteratively the derivation functor to the tautological module P
as often as indicated by the arity s and nally the suitable bre functor, glueing
everything together via the product on module categories.                                    However, we choose
not to, for reasons we explain now.                            Consider again the diagram of Disp. (3.3),
instantiated for the classic arity                    s:

                                          n
                                          Q
                                              [P si ]ti
                                                                       αP        / [P ]t                       (7.1)
                                                                                        0
                                      i=1


                                          [f si ]ti
                                  Q
                                                                                      ft0
                                      i


                                                      
                                          n                                           
                              f   ∗
                                          Q       si
                                              [Q ]ti                           / f ∗ [Q]t0
                                      i=1                          f ∗ (αQ )

This diagram actually makes use of many instances of the equalities mentioned in
Rem. 2.63, in order to justify composability of module morphisms. For instance,
in the lower right corner, the fact that pullback and bre may be permuted, is
used. In   Coq   the aforementioned equalities of modules hold propositionally (if one
uses appropriate axioms, such as proof irrelevance), but not denitionally, i.e. the
modules are not convertible (see also Rem. 2.64). In order to be able to compose
a module morphism with target                             ρ∗ [M ]u ,   for instance, with a module morphism
                          ∗
with source module       [ρ M ]u , one needs to insert a suitable isomorphism of mod-
ules            ∼ [ρ∗ M ]u . The carriers of these isomorphisms are families of identity
       ρ∗ [M ]u =
functions, respectively, since the carriers of the source and target modules are con-
vertible. In our formalization we would have to insert these isomorphisms (called

                                                                 Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
110     ·      B. Ahrens




PROD_PB, ITDER_PB                                     and           ITFIB_PB      in our      Coq    library) in order to make some
compositions typecheck  as illustrated by the diagram in Disp. (7.2)  which in
turn would result in quite a cumbersome formalization with decreased readability.
Instead we decide to implement the left vertical morphism from scratch. For this


                           n
                           Q
                                [P si ]ti
                                                                                       αP
                                                                                                                  / Pt0           (7.2)
                           i=1



                  Q        si
                    i [f      ]ti




                   Qn                   
                                                    ∗ Q)si ]
                       i=1 [(f                                 ti




                           ∼
                   Q
                      i [=]ti




                                            
                   Qn               ∗ (Qsi )]                                                                          f t0
                       i=1 [f                ti




                               ∼
                           Q
                             i=




                    Qn                          
                       i=1       f ∗ [Qsi ]ti



                               ∼
                               =



                                                                                                                      
                    f∗
                           Qn
                               i=1 [Q
                                                        si ]
                                                               ti
                                                                                      / f ∗ [Q]t0               / [f ∗ Q]t0
                                                                       ∗    Q                            ∼
                                                                                                         =
                                                                      f (α )




to work it is most convenient to dene the carrier of the product modules as an
inductive type, instead of applying the product in the module category recursively.
Hence also the product modules are built manually rather than using the categorical
devices of derivation, bre and product.

  7.1.2.1     Domain, Codomain, Representations.                                                    Given an arity

                                                          s = (s1 , t1 ), . . . , (sn , tn ) → t0
(or shorter   ` → t0 )      and a monad                                P,   we have to construct the module

                                                                                n
                                                                                Y                   Y
                                                       dom(s, P ) =                 [P si ]ti =          P .
                                                                                i=1                  `

Its carrier, being a kind of heterogeneous list, is given as an inductive type parame-
trized by a set family of variables and a list such as the list                                                ` indicating the domain
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                       Initiality for Typed Syntax and Semantics        ·     111




of an arity.   In fact, for dening the carrier, only an object map            M    of the type
indicated below is necessary:

Variable M : (ITYPE T) −> (ITYPE T).
Inductive prod_mod_c (V : ITYPE T) : [[T] ∗ T] −> Type :=
  | TTT : prod_mod_c V nil
  | CONSTR : forall b bs,
     M (V ∗∗ (fst b)) (snd b) −> prod_mod_c V bs −> prod_mod_c V (b::bs).
Now, for a list   l : [[T]∗T], if M is equipped with a module structure over a monad
P,   we equip the map       fun V => prod_mod_c V l with a module structure. Its
substitution   is given by a function pm_mkl, which is dened by recursion on the
argument of    type prod_mod_c ... , applying the module substitution of M in each
component:

Fixpoint pm_mkl l V W (f : V −−−> P W) (X : prod_mod_c M V l) :
                                               prod_mod_c M W l :=
     match X in prod_mod_c _ _ l return prod_mod_c M W l with
     | TTT => TTT M W
     | CONSTR b bs elem elems => CONSTR (M:=M) (V:=W)
                 (mkleisli (Module_struct := M) (lshift f) (snd b) elem)
                 (pm_mkl f elems)
     end.
Proving its module property  by induction on the argument     X  yields a module
prod_mod l     for each listl : [[T] ∗ T]. For s = ` → t0 , this denes the object
function of the functor dom(s). The object function of cod(s) is easy to dene,
since it simply associates, to any monad P , the bre module with respect to t0 of
the tautological module P . Again, this is dened more generally for any P module
M with codomain category SetT . Putting both domain and codomain together,
we associate, to any algebraic arity s and any P module M , a type of module
morphisms

                                   dom(s, M ) → cod(s, M )
as in Code 7.4 below.     Note that     M   is later instantiated by the tautological         P
module   P.
  Code 7.4.    (Representation of an Arity, Def. 3.25):

Variable M : Module P (ITYPE T).
Denition modhom_from_arity (ar : [[T] ∗ T] ∗ T) : Type :=
  Module_Hom (prod_mod M (fst ar)) (M [(snd ar)]).
where   M[(s)] denotes the bre of the module M over s. Finally a representation of
a signature  S in a monad P is given by a module morphism for each arity i, i.e. by
specifying a function of type

                               ∀s ∈ S, dom(s, P ) → cod(s, P ) ,
where   P   denotes the tautological     P module.    Since the set of arities is indexed
by the target type of the arities, the representation structure is indexed as well:


                                              Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
112     ·      B. Ahrens




  Code 7.5.    (Representation of a Signature, Def. 3.25):

Variable P : Monad (ITYPE T).
Denition Repr_t (t : T) :=
   forall i : sig_index (S t), modhom_from_arity P ((sig i), t).
Denition Repr := forall t, Repr_t t.
We bundle the data and dene a representation as a monad together with a repre-
                                            9
sentation structure over this monad :

Record Representation := {
  rep_monad :> Monad (ITYPE T);
  repr : Repr rep_monad }.

  7.1.2.2    Morphisms of Representations.             The carrier of the domain module
                                                        Y
                                        dom(s, P ) =          P
                                                         l

of a representation (cf. Disp. (7.1)) is dened as an inductive type. This suggests the
use of structural recursion for dening the left vertical morphism of the commutative
diagram of Disp. (7.1). Given a monad morphism
                 Q                                                f : P → Q,   we apply   f   to every
component of        ` P:

Fixpoint Prod_mor_c (l : [[T] ∗ T]) (V : ITYPE T) (X : prod_mod P l V) :
                 f∗ (prod_mod Q l) V :=
  match X in prod_mod_c _ _ l return f∗ (prod_mod Q l) V with
  | TTT => TTT _ _
  | CONSTR b bs elem elems =>
    CONSTR (f _ _ elem) (Prod_mor_c elems)
  end.
This function is easily proved to be a morphism of             P modules
                                                        Y           Y
                       dom(s, f ) := Prod_mor :              P → f∗   Q .
                                                         `             `

We thus are able to avoid mentioning all those trivial isomorphisms in the deni-
tion of the arrow map of the functor            dom(s)       that are present in the diagram of
Disp. (7.2).
  The codomain arrow        cod(s, f ) = ft0 is obtained by taking the bre module of the
module morphism induced by        f , cf. Sect. 2.2.2. The Coq function PbMod_ind_Hom
, which associates to any monad morphism the induced module morphism, can even
be declared as a coercion

Coercion PbMod_ind_Hom : Monad_Hom >−> mor.
such that the abuse of notation introduced in the informal Def. 2.52 has a counter-
part in the formal development.


9 Here an example of   coercion   occurs. The special notation :> allows us to omit the projection
rep_monad   when accessing the monad which underlies a given representation R. We can hence
also write R x for the value of the monad of R on an object x of the underlying category.

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                           Initiality for Typed Syntax and Semantics           ·     113




  The isomorphism in the lower right corner however remains in the formalization,
appearing as    ITPB_FIB.         Its underlying family of morphisms, however, is simply
a family of identity functions.          For an arity        a   and module morphisms         RepP   and
RepQ    representing this arity in monads           P   and      Q   respectively, the denition of the
commutative diagram reads as follows:

  Code 7.6.    (Commutative Diagram for Representation Morphism, Def. 3.26):

Denition commute f RepP RepQ : Prop :=
  RepP ;; f [(snd a)] == Prod_mor (fst a) ;; f∗ RepQ ;; ITPB_FIB f _ _
A morphism of representations from              P   to   Q    of the signature      S   is just a monad
morphism from       P   to   Q   together with the commutativity property for each arity.
More precisely, since arities are indexed by their target type, we have a commutative
diagram for any object type         t : T and each arity (index) i in the indexing set of S t:
  Code 7.7.    (Morphism of representations, Def. 3.26):

Variables P Q : Representation S.
Class Representation_Hom_struct (f : Monad_Hom P Q) :=
  repr_hom_s : forall t (i : sig_index (S t)), commute f (repr P i) (repr Q i).
Record Representation_Hom : Type := {
  repr_hom_c :> Monad_Hom P Q;
  repr_hom :> Representation_Hom_struct repr_hom_c }.
As mentioned in Sect. 3.2.2, representations of                  S   and their morphisms form a cate-
gory   REPRESENTATION S.            Composition of representations is dened by composing
the underlying monad morphisms:

Program Instance Rep_comp_struct :
    Representation_Hom_struct (Monad_Hom_comp f g).
where the commutation property is proved by some tactic dened beforehand. Ac-
cordingly, the identity morphism of representations is built upon the identity monad
morphism:

Program Instance Rep_Id_struct :
    Representation_Hom_struct (Monad_Hom_id P).
Since equality on morphisms of representations is dened as equality of the underly-
ing monad morphisms, the properties of composition necessary for representations
to form a category are a consequence of those for the category                   MONAD (ITYPE T).
The construction of the initial representation (and hence the proof of Thm. 3.28)
is explained in the next section.


7.2    Construction of the Initial Object
The initial object of the category of representations of the signature                  S is constructed
in several steps:

(1) the syntax associated to         S   as an inductive data type           STS,
(2) denition of a monad structure           STS_Monad on said data type,
(3) construction of the representation structure      STSRepr on STS_Monad,

                                                    Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
114       ·       B. Ahrens




(4) for any representation         R,   construction of morphism   init R   from   STSRepr    to   R,
(5) uniqueness of       init R   for any representation   R.
  7.2.1  The Terms Generated by a Signature. The rst step is to dene a map
STS : ITYPE T −−−> ITYPE T  the monad carrier  mapping each type family
V of variables to the type family of terms with free variables in V . Since objects of
ITYPE T really are dependent Coq types (cf. Code 6.5), this map is implemented as
a Coq inductive family of types, parametrized by a context and dependent on object
types. Apart from the use of dependent types, the data parts of this section could
indeed be done in any programming language featuring inductive types.
  Mutual induction is used, dening at the same time a type             STS_list of heteroge-
neous lists of terms, yielding the arguments to the constructors of        S . This list type
is indexed by arities, such that the constructors can be fed with precisely the right
kind of arguments.

  Code 7.8.       (Terms of the Initial Representation):

Inductive STS (V : ITYPE T) : ITYPE T :=
  | Var : forall t, V t −> STS V t
  | Build : forall t (i : sig_index (S t)), STS_list V (sig i) −> STS V t
with
 STS_list (V : ITYPE T) : [[T] ∗ T] −> Type :=
  | TT : STS_list V nil
  | constr : forall b bs,
      STS (V ∗∗ (fst b)) (snd b) −> STS_list V bs −> STS_list V (b::bs).
The constructor       Build   takes 3 arguments:

an object type        t   indicating its output type,

an arity     i   (resp. its index) from the set of indices with output type        t   and

a term of type        STS_list V (sig i)    carrying the subterms of the term to construct.

Note that     Coq    typing ensures the correct typing of all constructible terms of           STS
, a techique called         intrinsic typing.   The    Scheme   command generates a mutual
induction scheme for the dened pair of types. The latter type is actually isomorphic
to the type       prod_mod_c STS.          This duplication of data could hence have been
avoided by dening a nested inductive type as follows, instead of using mutual
induction.

 Inductive STS (V : ITYPE T) : ITYPE T :=
  | Var : forall t, V t −> STS V t
  | Build : forall t (i : sig_index (S t)), prod_mod_c STS V (sig i) −> STS V t.
However, we use the mutual inductive version because it allows us to dene functions
on those types by mutual recursion rather than by nested recursion; the latter are
signicantly more dicult to reason about.

  7.2.2   Monad Structure on the Set of Terms. We continue by dening a monad
structure on the map    STS. Again, due to our choice of implementing sets as Coq
types (cf. Code 6.5), the maps we need really are Coq functions. As in the special
case of ULC (cf. Ex. 2.36) and TLC (cf. Ex. 2.37), the monadic map η is given by the

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                    Initiality for Typed Syntax and Semantics         ·     115




variableasterm constructor    Var.   The substitution map     subst   is dened using two
helper functions   rename   (providing functoriality, cf. Rem. 2.66) and        _shift    (used
when substituting under binders, cf. Ex. 2.74).         Renaming and substitution are
implemented using mutual recursion on the mutually inductive data types              STS and
STS_list:
  Fixpoint rename V W (f : V −−−> W) t (v : STS V t):=
       match v in STS _ t return STS W t with
       | Var t v => Var (f t v)
       | Build t i l => Build (i:=i) (list_rename l f)
       end
with
    list_rename V t (l : STS_list V t) W (f : V −−−> W) : STS_list W t :=
         match l in STS_list _ t return STS_list W t with
         | TT => TT W
         | constr b bs elem elems =>
                  constr (elem //− ( f ^^ (fst b)))
                                     (elems //−− f)
         end
where "x //− f" := (rename f x)
and "x //−− f" := (list_rename x f).
...
(* a lot more code *)
...
Fixpoint subst (V W : ITYPE T) (f : V −−−> STS W) t (v : STS V t) :
    STS W t := match v in STS _ t return STS W t with
       | Var t v => f t v
       | Build t i l => Build (l >>== f)
       end
with
    list_subst V W t (l : STS_list V t) (f : V −−−> STS W) : STS_list W t :=
         match l in STS_list _ t return STS_list W t with
         | TT => TT W
         | constr b bs elem elems =>
            constr (elem >== (_lshift f)) (elems >>== f)
         end
where "x >== f" := (subst f x)
and "x >>== f" := (list_subst x f).
The monadic properties that the substitution should satisfy, are similar to the lem-
mas one would prove in order to establish programm correctness. As an example,
the third monad law reads as

 Lemma subst_subst V t (v : STS V t) W X (f : V −−−> STS W)
            (g : W −−−> STS X) :
     v >== f >== g = v >== f;; subst g.
Proof.
 (* script omitted *)
Qed.
                                            Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
116       ·     B. Ahrens




Its proof script is a typical example; most of those lemmas are proved using the
induction scheme       STSind    instantiated with suitable properties  followed by a
single custom tactic which nishes o the resulting subgoals, mainly by rewriting
with equalities proved beforehand. After a quite lengthy series of lemmas we obtain
that the function      subst   and the variableasterm constructor           Var   turn   STS   into a
monad:

Program Instance STS_monad : Monad_struct STS := {
  weta := Var ;
  kleisli := subst }.

  7.2.3  A Representation in the Monad of Terms. The representational structure
on  STS is dened using the Build constructor. For each arity i in the index set
sig_index (S t), we must give a morphism of modules from prod_mod STS (sig i)
to STS [(t)]. Since the constructor Build takes its argument from STS_list and not
from the isomorphic prod_mod STS, we precompose with one of the isomorphisms
between those two types:

Program Instance STS_arity_rep (t : T) (i : sig_index (S t)) :
  Module_Hom_struct (S := prod_mod STS (sig i)) (T := STS [(t)])
   (fun V X => Build (STSl_f_pm X)).
The only property to verify is the compatibility of this map with the module sub-
stitution, which we happily leave to            Coq.   We obtain a representation of       S:
Record STSRepr : REPRESENTATION S := Build_Representation (@STSrepr).

  7.2.4       Weak Initiality for the Representation in the Term Monad.                In the intro-
duction, we gave the equations that a morphism of representations of the natural
numbers should satisfy. Reading those equations as a rewrite system from left to
right yields a way to dene iterative functions on the natural numbers. This idea
is also used in order to dene a morphism from               STSRepr      to any representation        R
of the signature      S:   a term of     STS,   whose root is a constructor      Build t i   for some
object type     t   and an arity i, is mapped recursively to the image  of the recur-
sively computed argument  under the corresponding representation                      repr R i   of   R.
This denition for a morphism of representations will turn out to be the only one
possible, leading to uniqueness. Formally, the carrier            init   of what will be the initial
morphism from        STSRepr    to   R   is dened as a mutually recursive      Coq   function:

Fixpoint init V t (v : STS V t) : R V t :=
    match v in STS _ t return R V t with
    | Var t v => weta (Monad_struct := R) V t v
    | Build t i X => repr R i V (init_list X)
    end
with
 init_list l (V : ITYPE T) (s : STS_list V l) : prod_mod R l V :=
    match s in STS_list _ l return prod_mod R l V with
    | TT => TTT _ _
    | constr b bs elem elems => CONSTR (init elem) (init_list elems)
    end.
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                       Initiality for Typed Syntax and Semantics              ·    117




where the function    init_list   applies   init   to (heterogeneous) lists of arguments. We
have to show that this function is a morphism of monads and a morphism of repre-
sentations. A series of lemmas show that            init   commutes with renaming resp. lifting
(init_lift), shifting (init_shift) and substitution (init_kleisli):

Lemma init_lift V t x W (f : V −−−> W) : init (x //− f) = lift f t (init x).
Lemma init_shift a V W (f : V −−−> STS W) : forall (t : T) (x : opt a V t),
     init (x >>− f) = x >>− (f ;; @init _).
Lemma init_kleisli V t (v : STS V t) W (f : V −−−> STS W) :
  init (v >== f) = kleisli (f ;; @init _ ) t (init v).
The latter property is precisely one of the axioms of morphisms of monads (cf.
Def. 3.12, rectangular diagram). The second monad morphism axiom which states
compatibility with the    ηs   of the monads involved is fullled by denition of                  init
 it is exactly the rst branch of the pattern matching by which the function                      init
is dened. We hence have established that                  init   is (the carrier of ) a morphism of
monads:

Program Instance init_monadic : Monad_Hom_struct (P:=STSM) init.
Record init_mon := Build_Monad_Hom init_monadic.
Very much less work is then needed to show that                    init   also is a morphism of repre-
sentations:

Program Instance init_representic : Representation_Hom_struct init_mon.

  7.2.5    Uniqueness and Initiality.       Uniqueness of the morphism of representations
init_rep   (obtained from packaging         init_representic         into a record instance) is ex-
pressed by the following lemma:

Lemma init_unique : forall f : STSRepr −−−> R , f == init_rep.
Instead of directly proving the lemma, we prove at rst an unfolded version which
allows to directly apply the mutual induction scheme                      STSind:
Variable f : Representation_Hom STSRepr R.
Hint Rewrite one_way : n.
Ltac ttt := tt;
 (try match goal with [t:T, s : STS_list _ _ |−_] => rewrite <− (one_way s);
               let H:=fresh in assert (H:=repr_hom f (t:=t));
               unfold commute in H; simpl in H end);
               repeat (app (mh_weta f) || tinv || tt).

Lemma init_unique_prepa V t (v : STS V t) : f V t v = init v.
Proof.
  apply (@STSind
      (fun V t v => f V t v = init v)
      (fun V l v => Prod_mor f l V (pm_f_STSl v) = init_list v));
  ttt.
Qed.

                                                   Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
118        ·     B. Ahrens




Finally we declare an instance of the            Initial type class    for the category of represen-
tations    REPRESENTATION S               with STSRepr as initial      object and   init_rep R   as the
initial morphism towards any              other representation R.

     Code 7.9.    (Instance of Initial for Category of Representations):

Program Instance STS_initial : Initial (REPRESENTATION S) := {
  Init := STSRepr ;
  InitMor R := init_rep R }.
In this instance declaration, the proof eld              InitMorUnique is lled    automatically by
the   Program     feature, using the preceding lemma           init_unique.
7.3    Remarks
The nature of the theorem made it convenient for computer theorem proving: the
proofs are straightforward, carrying no surprises. Moreover, they are highly tech-
nical using (mutual) induction, something                 Coq   oers good support for.
     Some aspects remain unsatisfactory: using type classes and records simultane-
ously is at least confusing for the reader, even if there are reasons from the im-
plementor's point of view to do so.              Also, the weak support for nested induction
in   Coq   obliged us to use mutual induction instead, leading to some duplication of
data and hence another unnecessary source of confusion. Other aspects, such as
the implementation of syntax in an ecient way, i.e. without any extrinsic typing
device, could be done due to             Coq's good support for dependent types.
     According to       coqwc10   the   Coq les that are specic to the proved theorem consist
of approximately 400 lines of specication and 600 lines of proof. The proofs are
done in a semiautomated way, employing a proof style promoted by Chlipala in his
online book [Chl], as well as in a published user tutorial [Chl10]. An earlier version
using a more standard proof style included about 900 lines of proof. This reduction
is mainly due to the fact that proof automation also stimulates reuse of code  here
reuse of proof code  similarly to how polymorphism does for data structures and
functions. However, we do not claim to be experts in proof automation, nor do we
have one tactic to rule them all.


8.    INITIALITY FOR UNTYPED 2SIGNATURES, FORMALIZED
In this chapter we present the formalization in the proof assistant                 Coq of Thm. 4.34
of Sect. 4. We rst dene arities and 1signatures in terms of lists. Afterwards we
dene representations for 1arities and construct the initial such representation.
We then formalize inequations over 1signatures and construct, for any suitable
2signature, the initial representation. Finally we show how to specify the untyped
lambda calculus with beta reduction via a 2signature.

8.1    Arities by Lists
According to Def. 4.1, a 1signature consists of an indexing type and, for each index,
a list of natural numbers, indicating the number of arguments of a constructor, as
well as the number of variables bound in each argument. Formally, 1signatures


10 The tool    coqwc,   part of the standard Coq tools, counts the number of lines in a Coq source le,
classied into the 3 categories     specication, proof   and   comment.
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                Initiality for Typed Syntax and Semantics        ·        119




are an untyped version of Code 7.1.                  In the formalization they are simply called
signatures:

  Code 8.1.      (1Signature, Def. 4.1):

Notation "[ T ]" := (list T) (at level 5).
Record Signature : Type := {
  sig_index : Type ;
  sig : sig_index −> [nat] }.
Next we formalize context extension according to a natural number, cf. Sect. 2.4.3.
These denitions are important for the denition of the module morphisms we
associate to an arity, cf. below. Context extension is actually functorial. Given a
natural number      n   and a set of variables          V,   we recursively dene the set      V     ∗∗
                                                                                                          n   to
be the set   V   enriched with          n   additional variables.

  Code 8.2.      (Adding fresh variables):

Fixpoint pow (n : nat) (V : TYPE) : TYPE :=
  match n with
  | 0 => V
  | S n' => pow n' (option V)
  end.
Notation "V ∗∗ n" := (pow n V) (at level 10).
Fixpoint pow_map (l : nat) V W (f : V −−−> W) :
          V ∗∗ l −−−> W ∗∗ l :=
  match l return V ∗∗ l −−−> W ∗∗ l with
  | 0 => f
  | S n' => pow_map (^ f)
  end.
Notation "f ^^ l" := (pow_map (l:=l) f) (at level 10).

8.2    Representations of a 1Signature
Given a classic arity     s,   i.e. a list of natural numbers        s   (cf. Code 8.1), and a relative
monad    P   on the functor        ∆,   we dene the product module           Ps   as in Rem. 4.9. More
                               s
generally, we dene      M         for any     P module M     with codomain       Pre.   Analogously to
the implementation of Sect. 7, we build this module from scratch instead of relying
on the categorytheoretic constructions such as product and derivation functor for
the module categories, allowing us to omit the insertion of isomorphisms in the
style of Lem. 2.106 and 2.107.                 Given any module     M over a monad P from sets
to preordered sets, we dene the product type                   prod_mod_c as a dependent type
parametrized by a set of variables and dependent on a list of naturals. Actually we
dene at rst the carrier depending not on a module, but just on a carrier function
M.    The relation on the product is induced by that on                  M.




                                                       Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
120     ·      B. Ahrens




  Code 8.3.    (Product Module, Carrier map):

  Variable M : TYPE −> Ord.
  Inductive prod_mod_c (V : TYPE) : [nat] −> Type :=
    | TTT : prod_mod_c V nil
    | CONSTR : forall b bs,
            M (V ∗∗ b)−> prod_mod_c V bs −> prod_mod_c V (b::bs) .
  Notation "a −:− b" := (CONSTR a b) (at level 60).
  Inductive prod_mod_c_rel (V: TYPE) : forall n, relation (prod_mod_c M V n):=
    | TTT_rel : forall x y : prod_mod_c M V nil, prod_mod_c_rel x y
    | CONSTR_rel : forall n l, forall x y : M (V ∗∗ n),
             forall a b : prod_mod_c M V l, x << y −>
       prod_mod_c_rel a b −> prod_mod_c_rel (x −:− a) (y −:− b).
Note that the inxed  << is overloaded notation and denotes the relation of any
preordered set.     For any given list      a   of naturals and any setV of variables, the
set   prod_mod_c V a       equipped with the relation     prod_mod_c_rel V a is in fact a
preordered set. For the proof of transitivity we         rely on the Coq tactic dependent
induction,   thus on the axioms

JMeq.JMeq_eq : forall (A : Type) (x y : A), x ∼= y −> x = y
Eqdep.Eq_rect_eq.eq_rect_eq : forall (U : Type) (p : U)
                                (Q : U −> Type) (x : Q p)
                                (h : p = p), x = eq_rect p Q x p h
from the  Coq standard library.
  Now, if  M is not just a map of type TYPE −> Ord, but a module over some
relative monad P over Delta, we equip the product map with a modulic substitution
in form of a recursive function:

  Code 8.4.    (Product module, substitution):

Variable M : RMOD P Delta.
Fixpoint pm_mkl l V W (f : Delta V −−−> P W)
       (X : prod_mod_c (fun V => M V) V l) : prod_mod_c _ W l :=
     match X in prod_mod_c _ _ l return prod_mod_c (fun V => M V) W l
           with
     | TTT => TTT _ W
     | elem −:− elems =>
       rmkleisli (RModule_struct := M) (lshift _ f) elem −:− pm_mkl f elems
     end.
(* ... *)
Denition prod_mod (a : [nat]) := Build_RModule (prod_mod_struct a).
Afterwards we prove by induction that this map is indeed monotone with respect
to the preorder dened in Code 8.3. Altogether, Code 8.3 and 8.4 dene a module
prod_mod M l                   M : RMOD P Ord and any list of naturals l.
                  for any module
  To any arity ar : [nat] and a module M over a monad P we associate a type of
module morphisms modhom_from_arity ar M. Representing ar in M then means
giving a term of type modhom_from_arity ar M. Note that in the corresponding


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                        Initiality for Typed Syntax and Semantics          ·     121




Def. 4.13 we have dened representations in            monads   only. Indeed we instantiate       M
with the tautological module later.

  Code 8.5.    (Type of Representations of an Arity, Def. 4.13):

Variable P : RMonad Delta.
Denition modhom_from_arity (M : RModule P Ord) (ar : [nat]) : Type :=
     RModule_Hom (prod_mod M ar) M.
For the rest of the section, we suppose a signature   S to be given via a Coq section
variable, Variable S : Signature. As just mentioned, representing the signature S in
a monad P (cf. Def. 4.14) means providing a suitable module morphism for any
arity of S, i.e. providing, for any element of the indexing set sig_index S, a term of
type modhom_from_arity P (sig i):

  Code 8.6.    (Representation of 1Signature, Def. 4.14):

Denition Repr (P : RMonad Delta) :=
  forall i : sig_index S, modhom_from_arity P (sig i).
Record Representation := {
  rep_monad :> RMonad Delta ;
  repr : Repr rep_monad }.
The projecton    rep_monad       is declared as a     coercion by using the special syntax :>.
This coercion allows for abuse of notation in            Coq as we do informally according to
Def. 4.14. See the rst paragraph of Sect. 8.6 for a use of this abuse.

8.3   Morphisms of Representations
A morphism of representations from           P   to   Q   ist given by a monad morphism          f :
P → Q       between the underlying monads such that a diagram commutes for any
arity, cf. Def. 4.17. The main task in the implementation is to dene this diagram
for a given arity   `,   and, more specically, the left vertical morphism

                                 dom(`, f ) = f ` : P ` → f ∗ Q` .
using the notation of Rem. 4.9.            Since    P`    is dened as an inductive type, it
makes sense to dene       f`   by recursion on the inductive type underlying          P `,    named
prod_mod_c P V l         (cf. Code 8.3):

  Code 8.7.    (Carrier of Domain Module Morphism of Def. 4.17):

Variables P Q : RMonad Delta.
Variable f : RMonad_Hom P Q.
Fixpoint Prod_mor_c (l : [nat])(V : TYPE)(X : prod_mod_c (fun V => P V) V l):
                   (prod_mod_c _ V l) :=
  match X in prod_mod_c _ _ l
  return f∗ (prod_mod Q l) V with
  | TTT => TTT _ _
  | elem −:− elems => f _ elem −:− Prod_mor_c elems
  end.
Proving this map monotone is a simple exercise, as well as its commutation property
with substitution, yielding the aforementioned module morphism. Now we have all

                                                 Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
122     ·      B. Ahrens




the ingredients we need in order to dene the diagram of Def. 4.17. For an arity       a
the diagram reads as follows:

  Code 8.8.    (Commutative Diagram of Def. 4.17):

Variable a : [nat].
Variable RepP : modhom_from_arity P a.
Variable RepQ : modhom_from_arity Q a.
Notation "f ∗ M" := (# (PbRMOD f _ ) M).
Denition commute := Prod_mor a ;; f ∗ RepQ == RepP ;; f^.
Here   f^ denotes the module morphism induced by a monad morphism, cf. Def. 2.100.
Using the preceding denition, we dene morphisms of representations of S:
  Code 8.9.    (Morphism of Representations, Def. 4.17):

Variables P Q : Representation.
Class Representation_Hom_struct (f : RMonad_Hom P Q) :=
   repr_hom_s : forall i : sig_index S,
            commute f (repr P i) (repr Q i).
Record Representation_Hom : Type := {
  repr_hom_c :> RMonad_Hom P Q;
  repr_hom :> Representation_Hom_struct repr_hom_c }.

8.4    Category of Representations
In this section we describe in more detail the category of representations of a 1
signature, cf. Def. 4.19. The composition of morpisms of representations        f :P →Q
and   g:Q→R       is essentially done by composing the underlying monad morphisms.
One has to show that this morphism does indeed commute with the representation
morphisms of     P   and   R.   Similarly, the identity monad morphism of (the monad
underlying) a representation       P yields a morphism of    representations.   Fed with
some suitable lemma, the        Program framework does the   job for us:

  Code 8.10.     (Composition and Identity of Representations):

Variables P Q R : Representation S.
Variable f : Representation_Hom P Q.
Variable g : Representation_Hom Q R.
Program Instance Rep_comp_struct :
      Representation_Hom_struct (RMonad_comp f g).
Program Instance Rep_Id_struct : Representation_Hom_struct (RMonad_id P).
Since equality of morphisms of representations is dened as equality of the under-
lying monad morphisms, the categorical properties of compositition are established
already as part of the denition of the category       RMONAD F      for any functor   F.




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                         Initiality for Typed Syntax and Semantics         ·    123




     Code 8.11.    (Category of Representations, Def. 4.19):

Program Instance REP_struct : Cat_struct (@Representation_Hom S) := {
  mor_oid a c := eq_Rep_oid a c;
  id a := Rep_Id a;
  comp P Q R f g := Rep_Comp f g }.
Denition REP := Build_Cat REP_struct.

8.5     Initiality without Inequations
We construct the initial object of the category         REP (cf. Code 8.11).         In the informal
proof of Lem. 4.21 this initial object is the image under a left adjoint of the initial
object in a category of representations as dened in Sect. 3.2 with the set of object
sorts  T = {∗}.       For the formal proof we decide to implement the initial object
of   REP directly,   in order to obtain a compact formalization. However, the initial
object is constructed in a way similar to that of Sect. 7. The carrier of the initial
representation is just a simplied  because untyped  version of Code 7.8. The
only signicant dierence to Sect. 7 is that we equip the set of terms with the trivial
diagonal preorder by applying the functor          ∆,   in   Coq   called   Delta:
     Code 8.12.:
Inductive UTS (V : TYPE) : TYPE :=
  | Var : V −> UTS V
  | Build : forall (i : sig_index S), UTS_list V (sig i) −> UTS V
with
UTS_list (V : TYPE) : [nat] −> Type :=
  | TT : UTS_list V nil
  | constr : forall b bs,
      UTS (V ∗∗ b) −> UTS_list V bs −> UTS_list V (b::bs).
Notation "a −::− b" := (constr a b).
Denition UTS_sm V := Delta (UTS V).
We dene renaming and, built on top of renaming, substitution:

Fixpoint rename (V W: TYPE ) (f : V −−−> W) (v : UTS V):=
     match v in UTS _ return UTS W with
     | Var v => Var (f v)
     | Build i l => Build (l //−− f)
     end
with
  list_rename V t (l : UTS_list V t) W (f : V −−−> W) : UTS_list W t :=
       match l in UTS_list _ t return UTS_list W t with
       | TT => TT W
       | constr b bs elem elems => elem //− f ^^ b −::− elems //−− f
       end
where "x //− f" := (rename f x)
and "x //−− f" := (list_rename x f).


                                                Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
124     ·      B. Ahrens




  Fixpoint subst (V W : TYPE) (f : V −−−> UTS W) (v : UTS V) :
    UTS W := match v in UTS _ return UTS _ with
       | Var v => f v
       | Build i l => Build (l >>== f)
       end
  with
    list_subst V W t (l : UTS_list V t) (f : V −−−> UTS W) : UTS_list W t :=
         match l in UTS_list _ t return UTS_list W t with
         | TT => TT W
         | elem −::− elems =>
            elem >== _lshift f −::− elems >>== f
         end
  where "x >== f" := (subst f x)
  and "x >>== f" := (list_subst x f).
Accordingly, the denition of a monadic structure on           V 7→ ∆ UTS(V )      diers from
the monad     STS_monad       of Sect. 7.2 only in the occasional use of the functor          ∆
(Delta) on the morphisms  corresponding to the denition of the left adjoint for
Lem. 4.5:

  Code 8.13.     (Relative Monad Freely Generated by 1Signature):

Program Instance UTS_sm_rmonad : RMonad_struct Delta UTS_sm := {
  rweta c := #Delta (@Var c);
  rkleisli a b f := #Delta (subst f) }.
Canonical Structure UTSM := Build_RMonad UTS_sm_rmonad.
The monad      UTSM    is easily equipped with a representation of the signature        S;   the
carrier of the representation of      i : sig_index S   is given by the function

fun (X : prod_mod_c _ V (sig i)) => Build (i:=i) (UTSl_f_pm (V:=V) X)
that is, by the constructorBuild i of the type UTS, precomposed with an isomor-
phism  UTSl_f_pm from prod_mod_c UTS to UTS_list. We thus obtain a repre-
sentation UTSRepr of the signature S.
  Given another representation, say, R, of S, the morphism init from UTSRepr to R
is dened by recursion:

Fixpoint init V (v : UTS V) : R V :=
          match v in UTS _ return R V with
          | Var v => rweta (RMonad_struct := R) V v
          | Build i X => repr R i V (init_list X)
          end
with
 init_list l (V : TYPE) (s : UTS_list V l) : prod_mod R l V :=
     match s in UTS_list _ l return prod_mod R l V with
     | TT => TTT _ _
     | elem −::− elems => init elem −:− init_list elems
     end.


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                        Initiality for Typed Syntax and Semantics          ·        125




This map      init   is compatible with lifting and substitution in       UTSM     and   R,    respec-
tively:

Lemma init_lift V x W (f : V −−−> W) :
   init (x //− f) = rlift R f (init x).
Lemma init_kleisli V (v : UTS V) W (f : Delta V −−−> UTS_sm W) :
  init (v >== f) = rkleisli (f ;; @init_sm W) (init v).
where     init_sm W      is the (trivially) monotone version of       init W    the adjunct of
init W    under the adjunction of Lem. 2.18. The latter of those lemmas constitutes
an important part of the proof that           init is the carrier of a module morphism from
UTSM to R.      It is trivial to prove that    init is also compatible with the representation
structure of UTSRepr and R, thus the carrier of a morphism of representations called
init_rep : UTSRepr −−−> R. Afterwards uniqueness of init_rep is proved:
Lemma init_unique :forall f : UTSRepr −−−> R , f == init_rep.
Finally we establish initiality by an instance declaration of the corresponding class:

Program Instance UTS_initial : Initial (REP S) := {
  Init := UTSRepr ;
  InitMor R := init_rep R }.

8.6    Inequations and Initial Representation of a 2Signature
For a 1signature       S , an S -module is dened to be a functor from representations of
S   to the category whose objects are pairs of a monad      P and a module M over P , cf.
Def. 4.22. We do not need the functor properties, and use dependent types instead
of the cumbersome category of pairs, in order to ensure that a representation in a
monad     P   is mapped to a     P module.
    The below denition makes use of two            coercions.    Firstly, we may write           a : C
because the object projection of the category record (cf. Code 6.3) is declared
as a coercion. Secondly, the monad underlying any representation can be accessed
without explicit projection using the coercion in Code 8.6 we mentioned above.

Record S_Module := {
  s_mod :> forall R : REP S, RMOD R wOrd ;
  s_mod_hom :> forall (R T : REP S)(f : R −−−> T),
         s_mod R −−−> PbRMod f (s_mod T) }.
Notation "U @ f" := (s_mod_hom U f)(at level 4).
Note that we write        U@f   for the image of the morphism of representations              f   under
the   S module U.       Source and target module of        f   are implicit arguments in this
application.
    A half-equation is a natural transformation between              S -modules.     We need the
naturality condition in the following. Since we have not formalized                 S -modules       as
functors, we have to state naturality explicitly:




                                                 Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
126     ·      B. Ahrens




  Code 8.14.     (HalfEquation, Def. 4.22):

  Class half_equation_struct (U V : S_Module)
      (half_eq : forall R : REP S, U R −−−> V R) := {
    comm_eq_s : forall (R T : REP S) (f : R −−−> T),
        U @ f ;; PbRMod_Hom _ (half_eq T) == half_eq R ;; V @ f }.

Record half_equation (U V : S_Module) := {
  half_eq :> forall R : REP S, U R −−−> V R ;
  half_eq_s :> half_equation_struct half_eq }.
We now formalizeclassic S modules. Any list of natural numbers uniquely species
      S module, cf. Def. 4.26. Given a list of naturals codl, we call this S module
a classic
S_Mod_classic codl. A classic halfequation is any halfequation with a classic co-
domain, and a classic inequation is a pair of parallel classic halfequations (cf.
Def. 4.33):

Denition half_eq_classic (U : S_Module)(codl : [nat]) :=
                                half_equation U (S_Mod_classic codl).
Record ineq_classic := {
  Dom : S_Module ;
  Cod : [nat] ;
  eq1 : half_eq_classic Dom Cod ;
  eq2 : half_eq_classic Dom Cod }.
Give a representation      P   and a (classic) inequation   e,   we check whether   P   satises   e
by pointwise comparison (cf. Def. 4.31):

Denition satises_ineq (e : ineq_classic) (P : REP S) :=
 forall c (x : Dom e P c),
         eq1 _ _ _ x << eq2 _ _ _ x.
(* for a family of inequations indexed by a set A *)
Denition Inequations (A : Type) := A −> ineq_classic.
Denition satises_ineqs A (T : Inequations A) (R : REP S) :=
      forall a, satises_ineq (T a) R.
We formalize sets of classic inequations as pairs of an indexing type A together with
a term of type Inequations A, that is, a map from A to the type of classic inequations
ineq_classic. The category of representations of (S, A) is obtained as a full subcat-
egory of the category of representations of S . The following declaration produces
a subcategory from predicates on the type of representations and on the (depen-
dent) type of morphisms of representations, yielding the category             PROP_REP         of
representations of    (S, A):
Variable A : Type.
Variable T : Inequations A.
Program Instance Ineq_Rep : SubCat_compat (REP S)
     (fun P => satises_ineqs T P) (fun a b f => True).
Denition INEQ_REP : Cat := SubCat Ineq_Rep.


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                      Initiality for Typed Syntax and Semantics        ·     127




We now construct the initial object of    INEQ_REP.      The relation on the initial object
is dened precisely as in the paper proof, cf. Disp. (4.1):

Denition prop_rel_c X (x y : UTS S X) : Prop :=
      forall R : PROP_REP, init (FINJ _ R) x << init (FINJ _ R) y.
Here, FINJ _ R denotes the representation R as a representation of S, i.e. the injec-
tion of R in the category REP S of representations of S. The relation dened above
is indeed a preorder, and we dene the monad UTSP to be the monad whose un-
derlying sets are identical to UTSM, namely the sets dened by UTS, but equipped
with this new preorder. This monad UTSP is denoted by ΣA in the paper proof.
   The representation module morphisms of the initial representation UTSRepr can
be reused after having proved their compatibility with the new order, yielding
a representation     UTSProp.     An important lemma states that this representation
satises the inequations of     T:
Lemma UTSPRepr_sig_prop : satises_ineqs T UTSProp.
We have to explicitly inject the representation into the category of representations
of   (S, A):
Denition UTSPROP : INEQ_REP :=
 exist (fun R : Representation S => satises_ineqs T R) UTSProp
  UTSPRepr_sig_prop.
For building the initial morphism towards any representation             R : INEQ_REP,       we
rst build the corresponding morphism in the category of representations of         S:
Denition init_prop_re : UTSPropr −−−> (FINJ _ R) := ...
which we then inject, analogously to the initial representation, into the subcategory
of representations of   (S, A):
Denition init_prop : UTSPROP −−−> R := exist _ (init_prop_re R) I.
Finally we prove Thm. 4.34: An initial object of a category is given by an object
Init of this category, a map associating go any object R a morphism InitMor R : Init
 −−−> R, and a proof of uniqueness of any such morphism. We instanciate the
type class Initial for the category INEQ_REP of representations of (S, A):

Program Instance INITIAL_INEQ_REP : Initial INEQ_REP := {
  Init := UTSPROP ;
  InitMor := init_prop ;
  InitMorUnique := init_prop_unique }.
We check its type after closing all the sections  and thus abstracting from the
section variables:

Check INITIAL_INEQ_REP.
INITIAL_INEQ_REP
     : forall (S : Signature) (A : Type) (T : Inequations S A),
        Initial (INEQ_REP (S:=S) (A:=A) T)


                                             Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
128     ·      B. Ahrens




8.7 Λβ : Lambda Calculus with beta reduction
We implement the example 2signature              Λβ ,   cf. Ex. 4.38. Throughout this section,
we use use a custom notation in         Coq    for the datatype of lists:

Notation "[[ x ; .. ; y ]]" := (cons x .. (cons y nil) ..).
  In order to specify the 1signature   Λ (cf. Def. 4.11, Ex. 4.2), we rst dene an
indexing set Lambda_index consisting of two elements, ABS and APP. This indexing
set reects the fact that the signature Λ consists of two arities. The record instance
Lambda is a term of type Signature (cf. Code 8.1). The map sig Lambda then
associates the corresponding lists of naturals to each of these elements, according
to Ex. 4.2:

Inductive Lambda_index := ABS | APP.
Denition Lambda : Signature := {|
  sig_index := Lambda_index ;
  sig := fun x => match x with
                  | ABS => [[ 1 ]]
                  | APP => [[ 0 ; 0]]
                  end |}.
  The denition of the inequation         β   (cf. Ex. 4.32) is a more challenging task, since
a halfequation is not just an element of a simple datatype like a 1arity, but given
by suitable module morphisms.
  At rst, we dene the substitution of                one   variable (cf. Def. 4.27) as a half
equation. The carrier      subst_carrier      of the substitution is dened as in Def. 2.110.
Afterwards we prove that this carrier satises the properties of a module morphism,
that is, is compatible with substitution in the source and target modules.                After
abstracting from the section variableR, we obtain a function subst_module_mor
which, given any representation R of S, yields the substitution module morphism
associated to (the monad underlying) R.

Variable S : Signature.
Variable R : REP S.
Denition subst_carrier :
   (forall c : TYPE, (S_Mod_classic_ob [[1; 0]] R) c −−−>
           (S_Mod_classic_ob [[0]] R) c) := ...
Program Instance sub_struct : RModule_Hom_struct
   (M:=S_Mod_classic_ob [[1 ; 0]] R) (N:=S_Mod_classic_ob [[0]] R)
   subst_carrier.
Denition subst_module_mor := Build_RModule_Hom (sub_struct R).
The last step is to prove naturality, that is, the commutativity of the family of
diagrams of Code 8.14. We recall that we do not implement                S modules as functors,
but just as the data part of functors. This is why we put the word                naturality in
quotes. After the proof we dene our rst halfequation,               subst_half_eq.
Program Instance subst_half_s : half_equation_struct
   (U:= S_Mod_classic [[1 ; 0]]) (V:= S_Mod_classic [[0]]) subst_module_mor.
Denition subst_half_eq := Build_half_equation subst_half_s.
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                    Initiality for Typed Syntax and Semantics         ·    129




     The denition of the second halfequation of Ex. 4.28 is possible for any 1
signature with abstraction and application, such as the 1signature              Λ.   To keep
the example simple, we only dene the halfequation for            Λ.    The needed steps
are precisely the same as for the substitution halfequation, so we just give the
statements.

Denition beta_carrier :
   (forall c : TYPE, (S_Mod_classic_ob [[1; 0]] R) c −−−>
           (S_Mod_classic_ob [[0]] R) c) := ...
Program Instance beta_struct : RModule_Hom_struct
       (M:=S_Mod_classic_ob [[1 ; 0]] R)
       (N:=S_Mod_classic_ob [[0]] R)
   beta_carrier.
Denition beta_module_mor := Build_RModule_Hom beta_struct.
Program Instance beta_half_s : half_equation_struct
       (U:=S_Mod_classic Lambda [[1 ; 0]])
       (V:=S_Mod_classic Lambda [[0]])
   beta_module_mor.
Denition beta_half_eq := Build_half_equation beta_half_s.
In the end we package both halfequations into one inequation specifying the beta
rule of Ex. 4.32.

Denition beta_rule : ineq_classic Lambda := {|
  eq1 := beta_half_eq ;
  eq2 := subst_half_eq Lambda |}.
We can now associate a short name to the category of representations of            Λβ , where,
for increased clarity, we specify the implicit arguments:

Denition Lambda_beta_Cat := INEQ_REP
   (S:=Lambda)(A:=unit)(fun x : unit => beta_rule).
Note that our formal denition allows that an inequation appears multiple times
in a 2signature, whereas in the informal denition we have             sets   of inequations.
Unlike for arities, having several copies of the same inequation does not change the
resulting category neither the initial object, of course. The initial representation is
obtained via the specication

Denition Lambda_beta := @Init _ _ _
        (INITIAL_INEQ_REP (fun x : unit => beta_rule)).

9.    A FAITHFUL TRANSLATION OF PCF TO ULC
In this chapter we describe the implementation of the category of representations of
PCF,    equipped with reduction rules  we refer to it as    semantic PCF        from now on
 as described informally in Sect. A.2. We state the reduction rules more precisely
later. This theorem is an instance of Thm. 5.21 proved in Sect. 5. However, for the
implementation in    Coq   of this instance we make several simplications compared
to the general theorem:



                                           Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
130      ·     B. Ahrens




we do not dene a notion of 2signature, but specify directly a                         Coq   type of
  representations of semantic         PCF;
we use dependent        Coq    types to formalize arities of higher degree (cf. Def. 5.3),
  instead of relying on modules on categories with pointed index sets.                        A repre-
  sentation of an arity of degree        n   is thus given by a family of module morphisms
  (of degree zero), indexed       n   times over the respective object type as described in
  Rem. 5.6;

the relation on the initial object is not dened via the formula of Disp. (5.2),
  but directly through an inductive type, cf. Code 9.9, and various closures, cf.
  Code 9.10.


9.1     Representations of PCF
In this section we explain the formalization of representations of semantic                      PCF.
According to Def. 5.10 and Def. 5.20, such a representation consists of

(1) a representation of the types of          PCF   (in a   Coq   type   U),   cf. Ex. 3.4,

(2) a relative monad       P   over the functor     ∆U   (in the formalization:   IDelta U) and
(3) representations of the arities of        PCF (cf. Ex. 3.48), i.e.     morphisms of P modules
      with suitable source and target modules such that

(4) the inequations dening the reduction rules of                PCF    are satised.

A representation of     PCF should be a bundle, i.e. a record type, whose components
 or elds  are these 4 items. In order to ease the denitions, we rst dene
what a representation of the term signature of PCF in a monad P is, in the presence
of an SPCF monad (cf. Def. 5.1). Unfolding the denitions, we suppose given a type
Sorts, a relative monad P over IDelta Sorts and three operations on Sorts: a binary
function Arrow  denoted by an inxed  ∼∼>  and two constants Bool and
Nat.
Variable Sorts : Type.
Variable P : RMonad (IDelta Sorts).
Variable Arrow : Sorts −> Sorts −> Sorts.
Variable Bool : Sorts.
Variable Nat : Sorts.
Notation "a ∼∼> b" := (Arrow a b) (at level 60, right associativity).
In this context, a representation of         PCF    is given by a bunch of module morphisms
satisfying some conditions. We split the denition into smaller pieces. Note that
M[t] denotes the bre module of module M with respect to t, and d M // u denotes
derivation of module M with respect to u. The module denoted by a star ∗ is the
terminal module, which is the constant singleton module.




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                     Initiality for Typed Syntax and Semantics            ·    131




  Code 9.1.   (1Signature of    PCF):
  Class PCFPO_rep_struct := {
    app : forall u v, (P[u ∼∼> v]) x (P[u]) −−−> P[v];
    abs : forall u v, (d P // u)[v] −−−> P[u ∼∼> v];
    rec : forall t, P[t ∼∼> t] −−−> P[t];
    tttt : ∗ −−−> P[Bool];
     : ∗ −−−> P[Bool];
    nats : forall m:nat, ∗ −−−> P[Nat];
    Succ : ∗ −−−> P[Nat ∼∼> Nat];
    Pred : ∗ −−−> P[Nat ∼∼> Nat];
    Zero : ∗ −−−> P[Nat ∼∼> Bool];
    CondN: ∗ −−−> P[Bool ∼∼> Nat ∼∼> Nat ∼∼> Nat];
    CondB: ∗ −−−> P[Bool ∼∼> Bool ∼∼> Bool ∼∼> Bool];
    bottom: forall t, ∗ −−−> P[t]; (* continued later *)
These module morphisms are subject to some inequations specifying the reduction
rules of Sect. A.2, or, equivalently, Ex. 5.19. The beta rule reads as

  Code 9.2.   (Beta Rule for Representations of        PCF):
  beta_red : forall r s V y z, app r s V (abs r s V y, z) << y[∗:= z] ; (* tbc *)
where   y[∗:= z] is the substitution of the freshest variable (cf. Def. 2.111) as a special
case of simultaneous monadic substitution. The rule for the xed point operator
says that   Y(f ) ; f (Y(f )):
  Code 9.3.   (Inequation for Fixedpoint Operator):

  Rec_A: forall V t g, rec _ _ g << app t t V (g, rec _ _ g) ; (* tbc *)
The other inequations concern the arithmetic and logical constants of              PCF.   Firstly,
we have that the conditionals reduce according to the truth value they are applied
to:

  Code 9.4.   (Logic Inequations of      PCF   Representations):

  CondN_t: forall V n m,
    app _ _ _ (app _ _ _
         (app _ _ _ (CondN V tt, tttt _ tt), n), m) << n ;
  CondN_f: forall V n m,
    app _ _ _ (app _ _ _
         (app _ _ _ (CondN V tt,  _ tt), n), m) << m ;
  CondB_t: forall V u v,
    app _ _ _ (app _ _ _
         (app _ _ _ (CondB V tt, tttt _ tt), u), v) << u ;
  CondB_f: forall V u v,
    app _ _ _ (app _ _ _
         (app _ _ _ (CondB V tt,  _ tt), u), v) << v ; (* tbc *)
Furthermore, we have that      succ(n)   reduces to   n+1     (which in   Coq   is written    S n),
reduction of the   zero?   predicate according to whether its argument is zero or not,
and that the predecessor is postinverse to the successor function:

                                               Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
132     ·      B. Ahrens




  Code 9.5.    (Arithmetic Inequations of        PCF     Representations):

  Succ_red: forall V n,
     app _ _ _(Succ V tt, nats n _ tt) << nats (S n) _ tt ;
  Zero_t: forall V,
     app _ _ _(Zero V tt, nats 0 _ tt) << tttt _ tt ;
  Zero_f: forall V n,
     app _ _ _(Zero V tt, nats (S n) _ tt) <<  _ tt ;
  Pred_Succ: forall V n,
     app _ _ _(Pred V tt, app _ _ _ (Succ V tt, nats n _ tt)) << nats n _ tt;
  Pred_Z: forall V,
     app _ _ _(Pred V tt, nats 0 _ tt) << nats 0 _ tt }.
Unfortunately, at this stage of the denition, we were not able to introduce a more
convenient notation for application, neither to omit the arguments denoted by an
underscore as instances of implicit arguments. After abstracting over the section
variables we package all of this into a record type:

Record PCFPO_rep := {
  Sorts : Type;
  Arrow : Sorts −> Sorts −> Sorts;
  Bool : Sorts ;
  Nat : Sorts ;
  pcf_rep_monad :> RMonad (IDelta Sorts);
  pcf_rep_struct :> PCFPO_rep_struct pcf_rep_monad Arrow Bool Nat }.
Notation "a ∼∼> b" := (Arrow a b) (at level 60, right associativity).
The type    PCFPO_rep       later constitutes the type of objects of the category of rep-
resentations of semantic      PCF.
9.2   Morphisms of Representations
A morphism of representations (cf. Def. 5.11) is built from a morphism                   g   of   type
representations and a colax monad morphism over the retyping functor associated
to the map     g.   The implementation of retyping is explained in Code 6.6.                 In the
particular case of    PCF,   a morphism of representations from         P    to   R   consists of a
morphism of representations of the types of            PCF  with underlying map Sorts_map
 and a colax morphism of relative monads which makes commute the diagrams
of the form given in Def. 5.11. We rst dene the diagrams we expect to commute,
before packaging everything into a record type of morphisms. The context is given
by the following declarations:

Variables P R : PCFPO_rep.
Variable Sorts_map : Sorts P −> Sorts R.
Variable HArrow :
  forall u v, Sorts_map (u ∼∼> v) = Sorts_map u ∼∼> Sorts_map v.
Variable HBool : Sorts_map (Bool _ ) = Bool _ .
Variable HNat : Sorts_map (Nat _ ) = Nat _ .
Variable f : colax_RMonad_Hom P R
  (G1:=RETYPE Sorts_map) (G2:=RETYPE_PO Sorts_map)
  (RT_NT (fun t => Sorts_map t)).
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                           Initiality for Typed Syntax and Semantics        ·     133




We explain the commutative diagrams of Def. 5.11 for some of the arities. For the
successor arity we ask the following diagram to commute:

     Code 9.6.    (Commutative Diagram for Successor Arity):

Program Denition Succ_hom' :=
  Succ ;; f [(Nat ∼∼> Nat)] ;; Fib_eq_RMod _ _ ;; IsoPF ==
    ∗−−−>∗ ;; f ∗∗ Succ.
Here the morphism          Succ   refers to the representation of the successor arity either
of   P   (the rst appearance) or      R   (the second appearance)         Coq   is able to gure
this out itself.     The domain of the successor is given by the terminal module        ∗.
Accordingly, we have that         dom(Succ, f ) is the trivial module morphism with domain
and codomain given by the terminal module.                 We denote this module morphism
by    ∗−−−>∗.       The codomain is given as the bre of            f   of type   ι ⇒ ι.   The two
remaining module morphisms are isomorphisms which do not appear in the informal
description. The isomorphism   IsoPF is needed to permute bre with pullback (cf.
Lem. 2.108).                  Fib_eq_RMod M H takes a module M and a proof
                    The morphism
H of equality of two object types as arguments, say, H : u = v. Its output is an
isomorphism M[u] −−−> M[v]. Here the proof is of type

Sorts_map (Nat ∼∼> Nat) = Sorts_map Nat ∼∼> Sorts_map Nat
and      Coq   is able to gure out the proof itself. We expand on this kind of modules
in Sect. 9.3 The diagram for application uses the product of module morphisms,
denoted by an inxed         X:
     Code 9.7.    (Commutative Diagram for Application Arity):

Program Denition app_hom' := forall u v,
    app u v;; f [( _ )] ;; IsoPF ==
    (f [(u ∼∼> v)] ;; Fib_eq_RMod _ (HArrow _ _);; IsoPF )
          X
    (f [(u)] ;; IsoPF ) ;; IsoXP ;; f ∗∗ (app _ _ ).
In addition to the already encountered isomorphism                 IsoPF   we have to insert an
isomorphism        IsoXP   which permutes pullback and product (cf. Lem. 2.106). As a
last example, we present the property for the abstraction:

     Code 9.8.    (Commutative Diagram for Abstraction Arity):

Program Denition abs_hom' := forall u v,
    abs u v ;; f [( _ )] ==
    DerFib_RMod_Hom _ _ _ ;; IsoPF ;;
    f ∗∗ (abs (_ u) (_ v)) ;; IsoFP ;;
    Fib_eq_RMod _ (eq_sym (HArrow _ _ )) .
Here the module morphism      DerFib_RMod_Hom f u v corresponds to the morphism
dom(Abs(u, v), f ) = [f u ]v , and IsoFP permutes bre with pullback, just like its
sibling IsoPF, but the other way round.
     We bundle all those properties into a type class:




                                                  Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
134     ·        B. Ahrens




  Class PCFPO_rep_Hom_struct := {
    CondB_hom : CondB_hom' ;
    CondN_hom : CondN_hom' ;
    Pred_hom : Pred_hom' ;
    Zero_hom : Zero_hom' ;
    Succ_hom : Succ_hom' ;
    f_hom : f_hom' ;
    ttt_hom : ttt_hom' ;
    bottom_hom : bottom_hom' ;
    nats_hom : nats_hom' ;
    app_hom : app_hom' ;
    rec_hom : rec_hom' ;
    abs_hom : abs_hom' }.
Similarly to what we did for representations, we abstract over the section variables
and dene a record type of morphisms of representations from                   P   to   R   :

Record PCFPO_rep_Hom := {
  Sorts_map : Sorts P −> Sorts R ;
  HArrow : forall u v, Sorts_map (u ∼∼> v) = Sorts_map u ∼∼> Sorts_map v;
  HNat : Sorts_map (Nat _ ) = Nat R ;
  HBool : Sorts_map (Bool _ ) = Bool R ;
  rep_Hom_monad :> colax_RMonad_Hom P R (RT_NT Sorts_map);
  rep_colax_Hom_monad_struct :> PCFPO_rep_Hom_struct
                  HArrow HBool HNat rep_Hom_monad }.

9.3   Digression on Equal Fibre Modules in Coq
Suppose     Q                                   F : C → D and M is a Qmodule
                is a relative monad on some functor
with codomain       PreT .
                        u, t ∈ T and suppose given a proof H of the proposition
                             Let
u = t. We can now prove [M ]u = [M ]t , but unfortunately this is not sucient for
composing a morphism with codomain [M ]u with one whose domain is [M ]t in Coq
(cf. Sect. 6.3.1). Indeed, the problem we encounter here is even worse than that of
permutation of pullback with bre, derivation and products (see e.g. Sect. 7.1.2),
since not even the carriers of          [M ]u   and   [M ]t   are convertible.     This means that
the isomorphism we have to insert does not even allow for an underlying family of
identity    maps as carriers, but instead is a transport of the form             eq_rect.
  In more detail, the carrier of         M is a   map from the objects of          C to PreT ,      that
is, for each    c ∈ C,   its image   M c ∈ PreT   is basically a dependent type (with some
structure).      The bre is then simply computed by application.                  The carrier of a
module morphism          ρ : [M ]u → [M ]t   thus consists of a family of maps of sets indexed
by objects      c ∈ C,
                                     ρc : M (c)(u) → M (c)(t) .
In intensional type theory, we have an           explicit     cast operator   eq_rect       which allows
the denition of precisely such a map:

eq_rect : forall (A : Type) (x : A) (P : A −> Type),
      P x −> forall y : A, x = y −> P y
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                           Initiality for Typed Syntax and Semantics          ·        135




Note that this operator is equivalent to the operator                J   in Hofmann's PhD thesis
[Hof95], whose typing rule is called Id-Elim-J.
  Here we instantiate       A   by set of object types          T and the dependent         type   P   by
M (c),   allowing us to dene a map         transport    from   M (c)(u) to M (c)(t):
Variable T : Type.
Variables u t : T.
Variable M : RMOD Q (IPO T).
Hypothesis H : u = t.
Denition transport (c : C) : M c u −> M c t :=
   fun (s : M c u) => eq_rect u (fun t : T => (M c) t) s t H.
Fortunately it is possible to get rid of the transport via a computation rule equiva-
lent to a rule named Id-Comp in Hofmann's thesis. In                   Coq   this rule says that the
term

eq_rect u P a a eq_re
reduces to  and thus in particular is provably equal to  the term                    a   itself. Thus
a considerable part of proof code in the following is about elimination of explicit
casts. Indeed, the scheme is as follows: we start with a goal

 ______________________________________(1/1)
G
such that    G contains    a subterm       eq_rect u P a b H,      i.e. with   H : a = b.     We then
generalize   H, yielding   the goal

 ______________________________________(1/1)
forall H : a = b, G
Now rewriting with a proof of         a=b        (using a copy of   H)   turns the goal into

 ______________________________________(1/1)
forall H : a = a, G
After introducing    H,               H in the goal into eq_re using the axiom
                           we can rewrite
UIP_re    which says that any proof ofa = a is equal to eq_re. Thus the goal G
contains the subterm eq_rect u P a a eq_re, which simplies to a  the transport
has disappeared. Note that for the rewrite of forall H : a = b into forall H : a = a
in the goal, many other terms from the context have to be generalized, as well as
structures broken into their constituent pieces, in order to obtain sucient exibility
in the goal for the rewrite to result in a welltyped term.


9.4    Equality of Morphisms, Category of Representations
We have already seen how some denitions that are trivial in informal mathematics,
turn into something awful in intensional type theory.                    Equality of morphisms of
representations is another such denition.              Informally, two such morphisms             a, c :
P →R      of representations are equal if

(1) their map of object types         fa   and   fc (Sorts_map)     are equal and

(2) their underlying colax morphism of monads  also called                    a and c  are equal.

                                                    Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
136       ·      B. Ahrens




In our formalization, the second condition is not even directly expressable, since
these monad morphisms do not have the same type: we have, for a context                                   V ∈
SetP ,
                                            aV : f~a (P V ) → R(f~a V )
and

                                            cV : f~c (P V ) → R(f~c V ) .
where     SetP   is a notation for contexts typed over the set of object types the rep-
resentation      P   comes with, formally the type                Sorts P.       We can only compare       aV
to   cV   by composing each of them with a suitable transport                       transp     again, yielding
morphisms

                        R(transp) ◦ aV : f~a (P V ) → R(f~a V ) → R(f~c V )
and

                            cV ◦ transp' : f~a (P V ) → f~c (P V ) → R(f~c V ) .
As before, for equal bres[M ]u and [M ]t with u = t, the carriers of those transports
transp and transp' are terms of the form eq_rect _ _ _ H, where H is a proof term
which depends on the proof of

forall x : Sorts P, Sorts_map c x = Sorts_map a x
of the rst condition. Altogether, the denition of equality of morphisms of repre-
sentations is given by the following inductive proposition:

Inductive eq_Rep (P R : PCFPO_rep) : relation (PCFPO_rep_Hom P R) :=
 | eq_rep : forall (a c : PCFPO_rep_Hom P R),
             forall H : (forall t, Sorts_map c t = Sorts_map a t),
             (forall V, a V ;; rlift R (Transp H V)
                                          ==
                          Transp_ord H (P V) ;; c V ) −> eq_Rep a c.
The formal proof that the relation thus dened is an equivalence is inadequately long
when compared to its mathematical complexity, due to the transport elimination.
     Composition of representations is done by composing the underlying maps of
sorts, as well as composing the underlying monad morphisms pointwise. Again, this
operation, which is trivial from a mathematical point of view, yields a diculty in
the formalization, due to the fact that in the formalization

                                               ~g (f~V ) 6≡ (g ~◦ f )V .
More precisely, suppose given two morphisms of representations                                a : P → Q   and
b : Q → R,       given by families of morphisms indexed by                   V   resp.   W,
                                                      a
                                            aV : P
                                                 g V → Q(Ve a )        and
                                                      b
                                                       fb) ,
                                                 g → R(W
                                            bW : QW

where we write       Ve a   for   f~a V .   The monad morphism underlying the composite mor-
phism of representations is given by the following denition:

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                       Initiality for Typed Syntax and Semantics         ·     137




                                 b◦a
                           P V
                                              b◦aV
                                                           / R(Ve b◦a )
                                                                 O
                           g

                       match                                      R(∼
                                                                    =)

                                                             b
                            PV                              R Ve a
                                                               f
                                                               O
                        ctype                                     bVe a
                                                                    b
                               a
                           P V              / Q(Ve a )       / ^
                                                               ea
                                                       ctype Q(V )
                           g
                                       aV

or, in   Coq   code,

Denition comp_rep_car : (forall c : ITYPE U,
         RETYPE (fun t => f' (f t)) (P c) −−−>
    R ((RETYPE (fun t => f' (f t))) c)) :=
 fun (V : ITYPE U) t (y : retype (fun t => f' (f t)) (P V) t) =>
   match y with ctype _ z =>
      lift (M:=R) (double_retype_1 (f:=f) (f':=f') (V:=V)) _
            (b _ _ (ctype (fun t => f' t)
                 (a _ _ (ctype (fun t => f t) z ))))
    end.
where    double_retype_1   denotes the isomorphism in the upper right corner.                 The
proof of the commutative diagrams for the composite monad morphism is lengthy
due to the number of arities of the signature of           PCF.    Denition of the identity
morphisms is routine, and in the end we dene the category of representations of
semantic   PCF:
Program Instance REP_s :
     Cat_struct (obj := PCFPO_rep) (PCFPO_rep_Hom) := {
  mor_oid P R := eq_Rep_oid P R ;
  id R := Rep_id R ;
  comp a b c f g := Rep_comp f g }.

9.5   One Particular Representation
We dene a particular representation, which we later prove to be initial. First of
all, the set of object types of    PCF   is given as follows:

Inductive Sorts :=
  | Nat : Sorts
  | Bool : Sorts
  | Arrow : Sorts −> Sorts −> Sorts.
For this section we introduce some notations:

Notation "'TY'" := PCF.Sorts.
Notation "'IT'" := (ITYPE TY).
Notation "a '∼>' b" := (Arrow a b) (at level 69, right associativity).
                                               Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
138      ·        B. Ahrens




We specify the set of         PCF   constants through the following inductive type, indexed
by the sorts of      PCF:
Inductive Consts : TY −> Type :=
 | Nats : nat −> Consts Nat
 | ttt : Consts Bool | f : Consts Bool
 | succ : Consts (Nat ∼> Nat) | preds : Consts (Nat ∼> Nat)
 | zero : Consts (Nat ∼> Bool)
 | condN: Consts (Bool ∼> Nat ∼> Nat ∼> Nat)
 | condB: Consts (Bool ∼> Bool ∼> Bool ∼> Bool).
The set family of terms of          PCF   is given by an inductive family, parametrized by a
context      V   and indexed by object types:

Inductive PCF (V: TY −> Type) : TY −> Type:=
 | Bottom: forall t, PCF V t
 | Const : forall t, Consts t −> PCF V t
 | Var : forall t, V t −> PCF V t
 | App : forall t s, PCF V (s ∼> t) −> PCF V s −> PCF V t
 | Lam : forall t s, PCF (opt t V) s −> PCF V (t ∼> s)
 | Rec : forall t, PCF V (t ∼> t) −> PCF V t.
Notation "a @ b" := (App a b)(at level 43, left associativity).
Notation "M '" := (Const _ M) (at level 15).
Monadic substitution is dened recursively on terms:

Fixpoint subst (V W: TY −> Type)(f: forall t, V t −> PCF W t)
            (t : TY)(v : PCF V t) : PCF W t :=
    match v with
    | Bottom t => Bottom W t
    | c ' => c '
    | Var t v => f t v
    | u @ v => u >>= f @ v >>= f
    | Lam t s u => Lam (u >>= shift f)
    | Rec t u => Rec (u >>= f)
    end
where "y >>= f" := (@subst _ _ f _ y).
Here   shift f    is the substitution map    f   extended to account for an extended context
under the binder       Lam.    It is equal to the shifted map of Def. 2.102.
  Finally, we dene a relation on the terms of type          PCF via the inductive denition




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                        Initiality for Typed Syntax and Semantics        ·     139




  Code 9.9.      (Reduction Rules for    PCF):
  Inductive eval (V : IT): forall t, relation (PCF V t) :=
   | app_abs : forall (s t:TY) (M: PCF (opt s V) t) N,
                    eval (Lam M @ N) (M [∗:= N])
   | condN_t: forall n m, eval (condN ' @ ttt ' @ n @ m) n
   | condN_f: forall n m, eval (condN ' @ f ' @ n @ m) m
   | condB_t: forall u v, eval (condB ' @ ttt ' @ u @ v) u
   | condB_f: forall u v, eval (condB ' @ f ' @ u @ v) v
   | succ_red: forall n, eval (succ ' @ Nats n ') (Nats (S n) ')
   | zero_t: eval ( zero ' @ Nats 0 ') (ttt ')
   | zero_f: forall n, eval (zero ' @ Nats (S n)') (f ')
   | pred_Succ: forall n, eval (preds ' @ (succ ' @ Nats n ')) (Nats n ')
   | pred_z: eval (preds ' @ Nats 0 ') (Nats 0 ')
   | rec_a : forall t g, eval (Rec g) (g @ (Rec (t:=t) g)).
which we then propagate into subterms (cf. Code 9.10) and close with respect to
transitivity and reexivity:

  Code 9.10.      (Propagation of Reductions into Subterms):

  Reserved Notation "x :> y" (at level 70).
  Variable rel : forall (V:IT) t, relation (PCF V t).
  Inductive propag (V: IT) : forall t, relation (PCF V t) :=
  | relorig : forall t (v v': PCF V t), rel v v' −> v :> v'
  | relApp1: forall s t (M M' : PCF V (s ∼> t)) N, M :> M' −> M @ N :> M' @ N
  | relApp2: forall s t (M : PCF V (s ∼> t)) N N', N :> N' −> M @ N :> M @ N'
  | relLam: forall s t (M M':PCF (opt s V) t), M :> M' −> Lam M :> Lam M'
  | relRec: forall t (M M' : PCF V (t ∼> t)), M :> M' −> Rec M :> Rec M'
  where "x :> y" := (@propag _ _ x y).
The data thus dened constitutes a relative monad             PCFEM      on the functor      ∆TPCF
(IDelta   TY).   We omit the details.
  Now we need to dene a suitable morphism (resp. family of morphisms) of                PCFEM
modules for any arity (of higher degree). Let        α   be any such arity, for instance the
arity   App.   We need to verify two things:

(1) we show that the constructor of       PCF which corresponds to α is monotone with
    respect to the order on       PCFEM. For instance, we show that for any two terms
    r s:TY     and any   V : IDelta TY, the function
    fun y => App (fst y) (snd y): PCFEM V (r∼>s) x PCFEM V r −> PCFEM V s
    is monotone.

(2) We show that the monadic substitution dened above distributes over the con-
    structor in the sense of Ex. 2.74, i.e. we prove that the constructor is the carrier
    of a   module   morphism.

All of these are very straightforward proofs, resulting in a representation           PCFE_rep
of semantic      PCF:


                                               Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
140     ·      B. Ahrens




  Program Instance PCFE_rep_struct :
          PCFPO_rep_struct PCFEM PCF.arrow PCF.Bool PCF.Nat := {
    app r s := PCFApp r s;
    abs r s := PCFAbs r s;
    rec t := PCFRec t ;
    tttt := PCFconsts ttt ;
     := PCFconsts f;
    Succ := PCFconsts succ;
    Pred := PCFconsts preds;
    CondN := PCFconsts condN;
    CondB := PCFconsts condB;
    Zero := PCFconsts zero ;
    nats m := PCFconsts (Nats m);
    bottom t := PCFbottom t }.
  Denition PCFE_rep : PCFPO_rep := Build_PCFPO_rep PCFE_rep_struct.
  Note that in the instance declaration          PCFE_rep_struct,   the   Program   framework
proves automatically the properties of Code 9.2, 9.3, 9.4 and 9.5.


9.6   Initiality
In this section we dene a morphism of representations from    PCFE_rep to any
representation  R : PCFPO_rep. At rst we need to dene a map between the un-
derlying sorts, that is, a map Sorts PCFE_rep −> Sorts R. In short, each PCF type
goes to its representation in R:

Fixpoint Init_Sorts_map (t : Sorts PCFE_rep) : Sorts R :=
    match t with
    | PCF.Nat => Nat R
    | PCF.Bool => Bool R
    | u ∼> v => (Init_Sorts_map u) ∼∼> (Init_Sorts_map v)
    end.
The function       init   is the carrier of what will later be proved to be the initial mor-
phism to the representation          R.   It maps each constructor of   PCF   recursively to its
counterpart in the representation          R:




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                       Initiality for Typed Syntax and Semantics           ·     141




  Fixpoint init V t (v : PCF V t) :
       R (retype (fun t0 => Init_Sorts_map t0) V) (Init_Sorts_map t) :=
    match v with
    | Var t v => rweta R _ _ (ctype _ v)
    | u @ v => app _ _ _ (init u, init v)
    | Lam _ _ v => abs _ _ _ (rlift R
          (@der_comm TY (Sorts R) (fun t => Init_Sorts_map t) _ V ) _ (init v))
    | Rec _ v => rec _ _ (init v)
    | Bottom _ => bottom _ _ tt
    | y ' => match y in Consts t1 return
                  R (retype (fun t2 => Init_Sorts_map t2) V) (Init_Sorts_map t1)
                       with
                     | Nats m => nats m _ tt
                     | succ => Succ _ tt
                     | condN => CondN _ tt
                     | condB => CondB _ tt
                     | zero => Zero _ tt
                     | ttt => tttt _ tt
                     | f =>  _ tt
                     | preds => Pred _ tt
                     end
    end.
We write      iV for init V and g for Init_Sorts_map. Note that iV : PCF(V ) →
g ∗ (R(~g V )) really is the image of the initial morphism under the adjunction ϕ of
Def. 2.22. Intuitively, passing from init V= iV to its adjunct ϕ
                                                                   −1
                                                                      (iV ) is done by
precomposing with pattern matching on the constructor ctype (cf. Rem. 2.25). We
informally denote ϕ
                        −1
                           (iV ) by init V ◦ match.
   The map init is compatible with renaming and substitution in PCF and R, respec-
tively, in a sense made precise by the following two lemmas. The rst lemma states
that, for any morphism   f :V →W         in    SetTPCF ,    the following diagram commutes:

                                             PCF(f )
                         PCF(V )                              / PCF(W )

                          init V                                    init W
                                                               
                       g ∗ R(~g V )                           / g ∗ R(~g W ).
                                            g ∗ R(g ∗ f )


Lemma init_lift (V : IT) t (y : PCF V t) W (f : V −−−> W) :
  init (y //− f) = rlift R (retype_map f) _ (init y).
The next commutative diagram concerns substitution; for any                     f : V → PCF(W ),
the diagram obtained by applying        ϕ   to the diagram given in Disp. (5.5)  i.e. the
diagram corresponding to Disp. (5.6) , commutes:




                                                 Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
142        ·      B. Ahrens




                                                       σ PCF (f )
                         PCF(V )                                                 / PCF(W )

                           init V                                                      init W
                                                                                  
                         g ∗ R(Ṽ )                                              / g ∗ R(W̃ ).
                                            g ∗ σ R (ϕ−1 (init   W)◦(g∗ f ))
In   Coq     the lemma   init_subst         proves commutativity of this latter diagram:

Lemma init_subst V t (y : PCF V t) W (f : IDelta _ V −−−> PCFE W):
  init (y >>= f) =
     rkleisli (RMonad_struct := R)
          (SM_ind (V:= retype (fun t => _ t) V)
                   (W:= R (retype (fun t => _ t) W))
                   (fun t v => match v with ctype t p => init (f t p) end))
           _ (init y).
This latter lemma establishes almost the commutative diagram for the family
ϕ−1 (iV )      to constitute a (colax)        monad         morphism, which reads as follows:



                                                     g (σ PCF (f ))
                                                     ~
                       ~g (PCF(V ))                                            / ~g (PCF(W ))                  (9.1)

                     init V ◦ match                                                 init W ◦ match
                                                                                 
                              R(~g V )                                         / R(~g W ).
                                              σ R (init ◦   match ◦(~gf ))
Before we can actually build a monad morphism with carrier map                                       init V ◦ match,
we need to verify that         init      and thus its adjunct  is monotone. We do this in 3
steps, corresponding to the 3 steps in which we built up the preorder on the terms
of   PCF:
(1)   init   monotone with respect to the relation                    eval   (cf. Code 9.9):

      Lemma init_eval V t (v v' : PCF V t) : eval v v' −> init v <<< init v'.

(2)   init   monotone with respect to the propagation into subterms of                               eval;
      Lemma init_eval_star V t (y z : PCF V t) : eval_star y z −> init y <<< init z.

(3)   init   monotone with respect to reexive and transitive closure of above relation.

      Lemma init_mono c t (y z : PCFE c t) : y <<< z −> init y <<< init z.

We now have all the ingredients to dene the initial morphism from                                       PCF   to   R.
As already indicated by the diagram Disp. (9.1), its carrier is not given by just
the map        init, since this map does not have the right type: its domain is given, for
any context         V ∈ SetTPCF , by PCF(V ) and not, as needed, by ~g (PCF(V )). We thus
precompose with pattern matching in order to pass to its adjunct: for any context
V,    the carrier of the initial morphism is given by


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                     Initiality for Typed Syntax and Semantics           ·     143




fun t y => match y with
      | ctype _ p => init p
      end
 : retype _ (PCF V) −−−> R (retype _ W)
We recall that the constructor     ctype   is the carrier of the natural transformation
of the same name of Rem. 2.23, and that precomposing with pattern matching
corresponds to specifying maps on a coproduct via its universal property.
Putting the pieces together, we obtain a morphism of representions of semantic
PCF:
Denition initR : PCFPO_rep_Hom PCFE_rep R :=
        Build_PCFPO_rep_Hom initR_s.
Uniqueness is proved in the following lemma:

Lemma initR_unique : forall g : PCFE_rep −−−> R, g == initR.
The proof consists of two steps: rst, one has to show that the translation of               sorts
coincide. Since the source of this translation is an inductive type  the initial rep-
resentation of the signature of Ex. 3.4  this proof is done by induction. Afterwards
the translations of terms are proved to be equal. The proof is done by induction on
terms of   PCF.   It makes essentially use of the commutative diagrams (cf. Def. 5.11)
which we exemplarily presented for the arities of successor (Code 9.6), application
(Code 9.7) and abstraction (Code 9.8). Finally we can declare an instance of                 Initial
for the category   REP   of representations:

Instance PCF_initial : Initial REP := {
  Init := PCFE_rep ;
  InitMor R := initR R ;
  InitMorUnique R := @initR_unique R }.
Checking the axioms used for the proof of initiality (and its dependencies) yields the
use of nondependent functional extensionality (applied to the translations of sorts)
and uniqueness of identity proofs, which in the       Coq standard library is implemented
as a consequence of another  logically equivalent  axiom           eq_rect_eq:
Print Assumptions PCF_initial.
Axioms:
CatSem.AXIOMS.functional_extensionality.functional_extensionality :
    forall (A B : Type) (f g : A −> B),
                               (forall x : A, f x = g x) −> f = g
Eq_rect_eq.eq_rect_eq : forall (U : Type) (p : U) (Q : U −> Type)
                             (x : Q p) (h : p = p), x = eq_rect p Q x p h

9.7    A Representation of PCF in the Untyped Lambda Calculus
We use the iteration principle explained in Rem. 5.23 in order to specify a transla-
tion from   PCF   to the untyped lambda calculus which is compatible with reduction
in the source and target.      According to the principle, it is sucient to dene a
representation of    PCF   in the relative monad of the lambda calculus (cf. Exs. 1.2
and 2.85) and to verify that this representation satises the inequations of Fig. 7,

                                               Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
144     ·      B. Ahrens




formalized in the    Coq   code snippets 9.2, 9.3, 9.4 and 9.5. The rst task, specifying
a representation of the types of         PCF,                                  ULC, is trivial.
                                                in the singleton set of types of
We furthermore specify representations of the term arities of               PCF, presented in
Code 9.1, by giving an instance of the corresponding type class.

Program Instance PCF_ULC_rep_s :
 PCFPO_rep_struct (Sorts:=unit) ULCBETAM (fun _ _ => tt) tt tt := {
  app r s := ulc_app r s;
  abs r s := ulc_abs r s;
  rec t := ulc_rec t ;
  tttt := ulc_ttt ;
   := ulc_f ;
  nats m := ulc_N m ;
  Succ := ulc_succ ;
  CondB := ulc_condb ;
  CondN := ulc_condn ;
  bottom t := ulc_bottom t ;
  Zero := ulc_zero ;
  Pred := ulc_pred }.
Before taking a closer look at the module morphisms we specify in order to represent
the arities of   PCF, we note that in the above instance declaration, we have not given
the proofs corresponding to code snippets 9.2 to 9.5. In the terms of Rem. 5.23,
we have not completed the third task, the verication that the given representation
satises the inequations.          The   Program   feature we use during the above instance
declaration is able to detect that the elds called         beta_red, rec_A, etc., are missing,
and enters into interactive proof mode to allow us to ll in each of the missing elds.
  We now take a look at some of the lambda terms representing arities of                    PCF.
The carrier of the representations         ulc_app     is the application of lambda calculus, of
course, and similar for ulc_abs. Here the parameters r and s vary over terms of type
unit, the type of sorts underlying this representation. We use an inxed application
and a de Bruijn notation instead of the more abstract notation of nested data types:

Notation "a @ b" := (App a b) (at level 42, left associativity).
Notation "'1'" := (Var None) (at level 33).
Notation "'2'" := (Var (Some None)) (at level 24).
The truth values     T   and   F   are represented by

Eval compute in     ULC_True.
    = Abs (Abs      2)
Eval compute in     ULC_False.
    = Abs (Abs      1)
Natural numbers are given in Church style, the successor function is given by the
term   λnf x.f (n f x).    The predecessor is represented by the constant

                               λnf x.n (λgh.h(g f ))(λu.x)(λu.u),
and the test for zero is represented by         λn.n(λx.F )T , where F   and   T   are the lambda
terms representing     F   and   T,   respectively.

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                     Initiality for Typed Syntax and Semantics               ·        145




Eval compute in ULC_Nat 0.
    = Abs (Abs 1)
Eval compute in ULC_Nat 2.
    = Abs (Abs (2 @ (Abs (Abs (2 @ (Abs (Abs 1) @ 2 @ 1))) @ 2 @ 1)))
Eval compute in ULCsucc.
    = Abs (Abs (Abs (2 @ (3 @ 2 @ 1))))
Eval compute in ULC_pred.
    = Abs (Abs (Abs (3 @ Abs (Abs (1 @ (2 @ 4))) @ Abs 2 @ Abs 1)))
Eval compute in ULC_zero.
    = Abs (1 @ Abs (Abs (Abs 1)) @ Abs (Abs 2))
The conditional is represented by the lambda term                λpab.p a b:
Eval compute in ULC_cond.
    = Abs (Abs (Abs (3 @ 2 @ 1)))
The constant arity    ⊥A   is represented by         Ω:
Eval compute in ULC_omega.
    = Abs (1 @ 1) @ Abs (1 @ 1)
The xed point operator      Fix (rec)   is represented by the       Turing    xedpoint combi-
nator, that is, the lambda term

Eval compute in ULC_theta.
    = Abs (Abs (1 @ (2 @ 2 @ 1))) @ Abs (Abs (1 @ (2 @ 2 @ 1)))
The reason why we use the Turing operator instead of, say, the combinator                        Y,
Eval compute in ULC_Y.
    = Abs (Abs (2 @ (1 @ 1)) @ Abs (2 @ (1 @ 1)))
is that the latter does not have a property that is crucial for us: It is
                                                 ∗
                                    Θ(f )            f (Θ(f ))
but only
                                             ∗
                                    Y(f ) ! f (Y(f ))
via a common reduct. Thus if we would attempt to represent the arity                       rec   by the
xedpoint combinator      Y,   we would not be able to prove the condition expressed
in Code 9.3.     A way to allow for the use of            Y   as representation of   rec   would by
to consider   symmetric    relations on terms, e.g., relative monads into a category of
setoids.
  As a nal remark, we emphasize that while reduction is given as a relation in our
formalization, and as such is not computable, the obtained translation from                      PCF to
the untyped lambda calculus is executable in              Coq.   For instance, we can translate
the   PCF   term negating boolean terms as follows:

  Code 9.11.:
Eval compute in
  (PCF_ULC_c ((fun t => False)) tt (ctype _
   (Lam (condB ' @@ x_bool @@ f ' @@ ttt ')))).
   = Abs (Abs (Abs (Abs (3 @ 2 @ 1))) @ 1 @ Abs (Abs 1) @ Abs (Abs 2))
                                                 Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
146       ·      B. Ahrens




Here we use inxed  @@ to denote application of                PCF, and x_bool is simply a
notation for a de Bruijn variable of type           Bool of the lowest level, i.e. a variable that
is bound by the        Lam    binder of   PCF   in above term.


10.    CONCLUSIONS AND FURTHER WORK
We summarize the contributions of this thesis and discuss further work.

10.1      Contributions
We have proved an initiality result for             simplytyped syntax     equipped with    reduc-
tion rules.      The categorytheoretic iteration principle obtained through the uni-
versal property of initiality is suciently general to allow for the specication of
translations from the term representation to languages typed over                 dierent   sets of
sorts.
     We have characterized binding syntax with a reduction relation  for instance
the lambda calculus with beta reduction  as a                 relative monad    over the functor
∆    (cf. Ex. 2.85), encoding not only commutativity properties of substitution, but
also its      monotonicity    in the rstorder argument. By a suitable strengthening of
the denition of relative monad in a 2categorical context, an additional mono-
tonicity property for the higherorder argument of substitution can be assured, cf.
Rem. 2.86. We have also carried the denition of               module over a monad and several
constructions of modules over to modules over                relative monads.
     We then have proved several theorems in                the proof assistant Coq: rstly, we
implemented Zsidó's initiality theorem [Zsi10, Chap. 6], summed up in this work as
a reference in Sect. 3.2. Secondly, we have proved the initiality theorem of Sect. 4,
yielding a tool, which, when fed with a 2signature                 (S, A),   provides the syntax
associated to      S   equipped with the reduction relation generated by the inequations
of   A.   Thirdly, we have proved an instance of our main theorem, Thm. 5.21 of
Sect. 5, for the particular 2signature of the programming language                 PCF equipped
with reduction rules as in Fig. 7. The representation of the signature of             PCF in the
monad of the untyped lambda calculus with beta reduction results in an executable
translation from        PCF   to   ULC   which is certied to be compatible with substitution
and reduction in the source and target languages.

10.2      Further Work
In the future, we hope to prove and implement initiality theorems for richer type
systems.       In particular,      dependent    types and   polymorphism,     two important steps
towards certied programs and code reusability, respectively, should be accounted
for.
     Furthermore, the modelling of semantics should be improved to allow reasoning
about important properties such as              termination.
     As mentioned before, the implementation of initiality results in a proof assistant
may serve as a framework for research about programming languages and logics.
For this reason we envisage the implementation in a proof assistant of Thm. 5.21
in its full generality.
     We present these points in detail:

     Finegrained modelling of reduction.          For a given 2signature (a signature to-
gether with a set of inequations), models of this 2signature so far were basically

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                            Initiality for Typed Syntax and Semantics           ·     147




functors which associate, to any set of variables, a preordered set  intuitively
                                                         11
a model of terms over the set of variables                  .   The preorder   ≤   on such a model
corresponds to the reduction relation on the term model, i.e. the term                    t    reduces
to   t0   if and only if   t ≤ t0 .
     The modelling of reductions via         preorders   may be considered too coarse in several
aspects:
dierent reductions might lead from one term to another. However, the use of
     preorders to model reduction does not allow to distinguish two reductions with
     the same source and target.
The hardcoded reexivity rule makes reasoning about                     normalization      in par-
     ticular   termination      dicult.
     Instead of considering       preordered   sets (indexed by sets of free variables) as models
of a 2signature, it would thus be interesting to consider a structure which allows
for more negrained treatment of reduction, such as graphs or categories.                             In
other words, we might build models of 2signatures from relative monads into the
category of      graphs     or (small)   categories.   Using this new denition of model, one
might then envisage to prove an initiality theorem analogous to the one already
proven, and to use the additional structure obtained by switching to graphs or
categories to reason about the aforementioned properties.

     Inequations, Syntactically.         Fiore and Hur [FH10] develop a syntactic theory of
equations over a higherorder signature, allowing for proofs of soundness and com-
pleteness with respect to the models of the signature and the equations. Similar
techniques should allow for a syntactic presentation of our                      in equations.      Apart
from the obvious goal of soundness and completeness, such a syntactic presentation
would also facilitate the specication of reductions in the computer implementation
in   Coq:    in particular, it would make it possible to specify reductions without any
knowledge about categorytheoretic concepts.
     A minimal goal would be to have a data type  dependent on a 1signature 
which allows to specify the usual halfequations, mainly obtained from substitution
and from composition of arities, e.g.,           app ◦ (abs × id).     To a term of this data type,
on could associate a family of morphisms of modules which constitutes the carrier
of a halfequation: the algebraic properties (being a morphism of modules, which
corresponds to the compatibility of substitution with metasubstitution in [FH10],
could be proved once and for all by induction.

     More sophisticated type systems.          New programming languages tend to be equip-
ped with more and more sophisticated type systems:                       dependent types     allow to
ensure properties of function output and thus secure plugging together of functions.
Polymorphism         allows for the reuse of code in various situations.                An algebraic
characterization of such sophisticated type systems with variable binding via a
universal property is still missing. We hope to extend initiality results to encompass
these type systems.

     A wider class of arities.        The present initiality theorems encompass arities, i.e.
term constructors, of quite simple nature: the only operations considered are prod-


11 We ignore the typed case for the moment, which is analogous.




                                                    Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
148        ·     B. Ahrens




uct  for constructors with              multiple   arguments  and context extension, for mod-
elling variable binding.
     It would be desirable to consider more general term formers.                      Hirschowitz and
Maggesi [HM12] have introduced a notion of strengthened arity which allows, for
instance, to treat a term former of explicit attening                    µ : T ◦ T → T.      Ultimately,
we hope to nd a very general               simple    criterion for arities and signatures for which
an initial model can be provided.

     A certied research tool.           The obtained results should  as we have already done
for untyped syntax with reductions  be implemented in a theorem prover such as
Coq.      In this way, an initiality theorem may be used as a practical tool for easily
experimenting with dierent languages.                     Changing a language would be done by
simply changing its specifying signature, whereas all necessary data and properties
such as certied substitution and iteration, but also reductions, would be provided
by the system. For this computer implementation and suitable reduction rules, it
would also be desirable to obtain automatically a reduction                    function r     in addition
to the reduction relation. This reduction function might be validated against the
relation in the sense that one may prove that for any term                    t,   one has   t ≤ r(t).

A.     SYNTAX AND SEMANTICS OF LAMBDA CALCULUS AND PCF
The following section informally introduces the syntax and semantics of                          PCF     and
ULC,      as it might be introduced in some computer science textbook. Our presen-
tation of the lambda calculus is inspired by Barendregt and Barendsen's course
[BB94], and that of           PCF   by Hyland and Ong's paper [HO00].


A.1       Syntax of Lambda Calculus and PCF
Let   V    be a countably innite set (of variables). The syntax of                 ULC   is given by

                                         Λ ::=       v | Λ@Λ | λv.Λ ,
where      v∈V     varies over variables.
     The programming language               PCF     is a   typed   language, more precisely a     simply
typed     language. It is given by

a set of      sorts,
a set of      terms    and

a    typing   map associating a sort to any term.

     We take the presentation of           PCF from Hyland and Ong's paper on full abstraction
[HO00]. The sorts of          PCF    are constructed from two base sorts and a function type
constructor:

                                    TPCF ::= ι | o | TPCF ⇒ TPCF .
     The   terms   of   PCF   are dened in two steps: at rst, we dene a set of             raw    terms,
which actually contains more elements than we want.                          Afterwards, we dene a
welltypedness      predicate on those raw terms. The terms of                 PCF    then are the well
typed raw terms. The raw terms of                   PCF    are given by the grammar of Fig. 4.
     Note that we use the same inx notation _@_ for application in                       PCF   and   ULC.
We also write       f (x)   for   f @x   when no confusion can arise. The constants             cA   of sort


Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                                Initiality for Typed Syntax and Semantics            ·    149




                              s       ::=     ⊥A              undened
                                       |      cA              constant
                                       |      xA              variable
                                       |      s@s             application
                                       |      λx : A.s        abstraction
                                       |      FixA (s)        xed point operator




                                            Fig. 4.    Grammar of        PCF

A are the basic constants from logic and arithmetic, i.e. booleans T and F, natural
numbers n, successor and predecessor as well as test for zero, and conditionals.
They are listed in Fig. 5.



                          n       :        ι                     naturals (for    n ∈ N)
                       T, F       :        o                     boolean constants
                          S       :        ι⇒ι                   successor
                       pred       :        ι⇒ι                   predecessor
                      zero?       :        ι⇒o                   test on zero
                     condι        :        o⇒ι⇒ι⇒ι               conditional for naturals
                     condo        :        o⇒o⇒o⇒o               conditional for booleans




                                            Fig. 5.    Constants of      PCF

  Instead of all raw terms from the denition of Fig. 4 we only consider                           welltyped
terms, that is, those raw terms that are typable according to the typing judgements
of Fig. 6.



                cA : A                        ⊥A : A
              M :A⇒A                     M : A2                          M : A1 ⇒ A2      N : A1
             FixA (M ) : A        λx : A1 .M : A1 ⇒ A2                          M @N : A2


                                           Fig. 6.    Typing rules of     PCF


A.2   Semantics of Lambda Calculus and PCF
Functional programming languages such as                        PCF and ULC allow for computation by
reduction, as explained       in Sect. 1.2.6. The prime example of              reduction rule is the
beta rule of ULC,
                                      (λx.M )N            β    M [x := N ] ,                             (A.1)

where   M [x := N ] denotes the term M where free occurrences of the variable x have
been replaced by   N in a captureavoiding manner.
  The above rule may be considered to generate beta reduction in the sense that
we also consider

(1) reductions in     sub terms        such as in       λx.(λy.M )N         and


                                                          Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
150      ·     B. Ahrens




                                    λx : A.M (N )      M [x := N ]
                                            Fix(g)     g(Fix(g))
                                              S(n)     n+1
                                           pred(0)     0
                                      pred(  S(n))     n
                                           zero?(0)    T
                                     zero?(S(n))       F
                              condσ (T)(M )(N )        M   (σ ∈ {o, ι})
                              condσ (F)(M )(N )        N   (σ ∈ {o, ι})



                                 Fig. 7.    Reduction rules of   PCF

(2)   chains of reductions,    that is, reductions consisting of multiple steps.

Thus, to be more precise, what is usually called beta reduction, is in fact the
closure of the relation specied by the rule given in Disp. (A.1) under propagation
into subterms as well as transitivity and reexivity, denoted by          β   in Barendregt
and Barendsen's course [BB94]. In general we associate three dierent relations to
any set of reduction rules, see Sect. 1.2.6.
  Reduction in      PCF    is given by a beta rule similar to Disp. (A.1) and several
additional reduction rules concerning the xed point operator and the logical and
arithmetic constants. We list them in Fig. 7 using a smallstep semantics as given
in [HO00] or in Pitts' lecture notes on denotational semantics [Pit99]. Analogously
to the lambda calculus with beta reduction, we denote by  PCF  the reduction
relation obtained as closure under propagation into subterms as well as reexivity
and transitivity.




Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                   Initiality for Typed Syntax and Semantics        ·      151




References
     +
[ABF 05]     Brian E. Aydemir, Aaron Bohannon, Matthew Fairbairn, J. Nathan
             Foster, Benjamin C. Pierce, Peter Sewell, Dimitrios Vytiniotis, Ge-
             orey Washburn, Stephanie Weirich, and Steve Zdancewic.                 Mecha-
             nized metatheory for the masses: The POPLmark Challenge. In  In-
             ternational Conference on Theorem Proving in Higher Order Logics
             (TPHOLs), August 2005.
[ACU10]      Thorsten Altenkirch, James Chapman, and Tarmo Uustalu. Monads
             Need Not Be Endofunctors.       In C.-H. Luke Ong, editor,         FOSSACS,
             volume 6014 of     Lecture Notes in Computer Science,         pages 297311.
             Springer, 2010.

[Acz93]      Peter Aczel. Galois: A Theory Development Project. Technical Report
             for the 1993 Turin meeting on the Representation of Mathematics in
             Logical Frameworks., 1993.

[Ahr11]      Benedikt Ahrens.     Modules over relative monads for syntax and se-
             mantics. 2011. To be published in Math. Struct. in Comp. Science,
             arXiv:1107.5252.

[Ahr12]      Benedikt Ahrens. Extended Initiality for Typed Abstract Syntax.              Log-
             ical Methods in Computer Science,      8(2):1  35, 2012.

[AR99]       Thorsten Altenkirch and Bernhard Reus.           Monadic Presentations of
             Lambda Terms Using Generalized Inductive Types. In Jörg Flum and
             Mario Rodríguez-Artalejo, editors,    CSL, volume 1683 of Lecture Notes
             in Computer Science,    pages 453468. Springer, 1999.

[AZ11]       Benedikt Ahrens and Julianna Zsidó.         Initial Semantics for higher
             order typed syntax in Coq.   Journal of Formalized Reasoning, 4(1):25
             69, September 2011.

[BB94]       Henk Barendregt and Erik Barendsen. Introduction to Lambda Calcu-
             lus.   ftp://ftp.cs.ru.nl/pub/CompMath.Found/lambda.pdf , 1994.            revised
             2000.

[BHKM11]     Nick Benton, Chung-Kil Hur, Andrew Kennedy, and Conor McBride.
             Strongly Typed Term Representations in Coq.           Journal of Automated
             Reasoning,    pages 119, 2011. 10.1007/s10817-011-9219-0.

[Bir35]      Garrett Birkho.     On the Structure of Abstract Algebras.           In    Proc.
             Cambridge Phil. Soc.,   volume 31, pages 433454, 1935.

[BM98]       Richard S. Bird and Lambert Meertens. Nested Datatypes. In Johan
             Jeuring, editor,   LNCS 1422: Proceedings of Mathematics of Program
             Construction,   pages 5267, Marstrand, Sweden, June 1998. Springer-
             Verlag.

[BP99]       Richard S. Bird and Ross Paterson. De Bruijn Notation as a Nested
             Datatype.    J. Funct. Program.,   9(1):7791, 1999.
     +
[CAA 86]     Robert L. Constable, Stuart F. Allen, S. F. Allen, H. M. Bromley,
             W. R. Cleaveland, J. F. Cremer, R. W. Harper, Douglas J. Howe, T. B.
             Knoblock, N. P. Mendler, P. Panangaden, Scott F. Smith, James T.
             Sasaki, and S. F. Smith.     Implementing mathematics with the Nuprl

                                          Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
152       ·    B. Ahrens




               proof development system.          Prentice-Hall, Inc., Upper Saddle River,
               NJ, USA, 1986.

[CF09]         Venanzio Capretta and Amy Felty.           Higher-order abstract syntax in
               type theory. In S. Barry Cooper, Herman Geuvers, Anand Pillay, and
               Jouko Väänänen, editors,        Logic Colloquium 2006, volume 32 of Lecture
               Notes in Logic,     pages 6590. Cambridge University Press, 2009.

[Chl]          Adam Chlipala. Certied Programming with Dependent Types.             http:
               //adam.chlipala.net/cpdt/.
[Chl10]        Adam Chlipala. An Introduction to Programming and Proving with
               Dependent Types in Coq.         Journal of Formalized Reasoning, 3(2):193,
               December 2010.

[Chu36]        Alonzo Church. An unsolvable problem of elementary number theory.
               American Journal of Mathematics, 58(2):345363, 1936.
[Coq10]        Coq. The Coq Proof Assistant. http://coq.inria.fr, 2010.

[FH07]         Marcelo P. Fiore and Chung-Kil Hur.           Equational systems and free
               constructions (extended abstract).         In Lars Arge, Christian Cachin,
               Tomasz Jurdzinski, and Andrzej Tarlecki, editors,          ICALP,   volume
               4596 of   Lecture Notes in Computer Science,      pages 607618. Springer,
               2007.

[FH10]         Marcelo P. Fiore and Chung-Kil Hur. Second-order equational logic
               (extended abstract). In Anuj Dawar and Helmut Veith, editors,         CSL,
               volume 6247 of       Lecture Notes in Computer Science,     pages 320335.
               Springer, 2010.

[Fio02]        Marcelo Fiore. Semantic analysis of normalisation by evaluation for
               typed lambda calculus.    In Proceedings of the 4th ACM SIGPLAN
               international conference on Principles and practice of declarative pro-
               gramming, PPDP '02, pages 2637, New York, NY, USA, 2002. ACM.
[FPT99]        Marcelo Fiore, Gordon Plotkin, and Daniele Turi. Abstract syntax and
                                  Proceedings of the 14th Annual IEEE Symposium
               variable binding. In
               on Logic in Computer Science, LICS '99, pages 193202, Washington,
               DC, USA, 1999. IEEE Computer Society.

[GGMR09]       François Garillot, Georges Gonthier, Assia Mahboubi, and Laurence
               Rideau. Packaging Mathematical Structures. In Proceedings of the
               22nd International Conference on Theorem Proving in Higher Or-
               der Logics, TPHOLs '09, pages 327342, Berlin, Heidelberg, 2009.
               Springer-Verlag.

[GH08]         Murdoch J. Gabbay and Martin Hofmann. Nominal renaming sets. In
               Iliano Cervesato, Helmut Veith, and Andrei Voronkov, editors,       LPAR,
               volume 5330 of       Lecture Notes in Computer Science,     pages 158173.
               Springer, 2008.

[GL03]         Neil Ghani and Christoph Lüth. Rewriting via coinserters.         Nord. J.
               Comput.,     10(4):290312, 2003.

[GP99]         Murdoch J. Gabbay and Andrew M. Pitts. A New Approach to Ab-
               stract Syntax Involving Binders. In       14th Annual Symposium on Logic

Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                  Initiality for Typed Syntax and Semantics         ·     153




           in Computer Science,     pages 214224, Washington, DC, USA, 1999.
           IEEE Computer Society Press.

[GTL89]    Jean-Yves Girard, Paul Taylor, and Yves Lafont.              Proofs and types.
           Cambridge University Press, New York, NY, USA, 1989.

[GTWW77] J. A. Goguen, J. W. Thatcher, E. G. Wagner, and J. B. Wright. Ini-
           tial Algebra Semantics and Continuous Algebras.            J. ACM,     24:6895,
           January 1977.

[Hir]      Tom Hirschowitz.       Cartesian closed 2-categories and permutation
           equivalence in higher-order rewriting. 19 pages, submitted.

[HM07a]    André Hirschowitz and Marco Maggesi.             Modules over monads and
           linearity.   In Daniel Leivant and Ruy J. G. B. de Queiroz, editors,
           WoLLIC,      volume 4576 of   Lecture Notes in Computer Science,             pages
           218237. Springer, 2007.

[HM07b]    André Hirschowitz and Marco Maggesi.                The algebraicity of the
           lambda-calculus.     CoRR,    abs/0704.2900, 2007. informal publication;
           informal publication.

[HM10a]    André Hirschowitz and Marco Maggesi.             Modules over monads and
           initial semantics.   Inf. Comput.,   208(5):545564, 2010.

[HM10b]    André   Hirschowitz     and   Marco    Maggesi.       Nested    Abstract     Syn-
           tax in Coq.      Journal of Automated Reasoning,            pages 118, 2010.
           10.1007/s10817-010-9207-9.

[HM12]     André Hirschowitz and Marco Maggesi. Initial Semantics for Strength-
                                                                   Proceedings
           ened Signatures. In Dale Miller and Zoltán Ésik, editors,
           8th Workshop on Fixed Points in Computer Science, Tallinn, Estonia,
           24th March 2012, volume 77 of Electronic Proceedings in Theoretical
           Computer Science, pages 3138. Open Publishing Association, 2012.
[HO00]     J. M. E. Hyland and C.-H. Ong. On full abstraction for PCF: I. Models,
           observables and the full abstraction problem II. Dialogue games and
           innocent strategies III. A fully abstract and universal game model.
           Information and Computation, 163:285408, 2000.
[Hof95]    Martin Hofmann.   Extensional concepts in intensional type theory. PhD
           thesis, University of Edinburgh, Scotland, 1995. http://www.lfcs.inf.
           ed.ac.uk/reports/95/ECS-LFCS-95-327/.
[Hof99]    Martin Hofmann. Semantical Analysis of Higher-Order Syntax. In In
           14th Annual Symposium on Logic in Computer Science, pages 204
           213. IEEE Computer Society Press, 1999.

[HS98]     Gérard Huet and Amokrane Saïbi. Constructive Category Theory. In
           In Proceedings of the Joint CLICS-TYPES Workshop on Categories
           and Type Theory, Goteborg. MIT Press, 1998.
[Hur10]    Chung-Kil Hur. Categorical equational systems: algebraic models and
           equational reasoning. PhD thesis, University of Cambridge, UK, 2010.
[Lei04]    Tom Leinster. Higher Operads, Higher Categories. London Mathe-
           matical Society Lecture Note Series 298. Cambridge University Press,
           Cambridge, 2004.


                                          Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
154       ·    B. Ahrens




[ML98]         Saunders Mac Lane.     Categories for the working mathematician, vol-
               ume 5 of    Graduate Texts in Mathematics. Springer-Verlag, New York,
               second edition, 1998.

[MLM92]        Saunders Mac Lane and Ieke Moerdijk.           Sheaves in geometry and logic.
               Universitext. Springer-Verlag, New York, 1992. A rst introduction to
               topos theory.

[MS03]         Marino Miculan and Ivan Scagnetto. A framework for typed HOAS
               and semantics. In      PPDP,     pages 184194. ACM, 2003.

[O'K04]        Greg O'Keefe.       Towards a Readable Formalisation of Category The-
               ory.   Electronic Notes in Theoretical Computer Science,       91:212  228,
               2004. Proceedings of Computing: The Australasian Theory Sympo-
               sium (CATS) 2004.

[Pau88]        Lawrence C. Paulson.           Isabelle:   The next seven hundred theorem
               provers.     In Ewing L. Lusk and Ross A. Overbeek, editors,         CADE,
               volume 310 of       Lecture Notes in Computer Science,       pages 772773.
               Springer, 1988.

[Pho93]        Wesley Phoa.       Adequacy for untyped translations of typed lambda-
               calculi. In   LICS,   pages 287295. IEEE Computer Society, 1993.

[Pit99]        Andrew M. Pitts.         Lecture Notes on Denotational Semantics.       http:
               //www.cl.cam.ac.uk/teaching/Lectures/dens/,          1999.

[Plo77]        Gordon D. Plotkin. LCF considered as a programming language.            The-
               oretical Computer Science,        5(3):223255, 1977.

[Rie93]        Jon G. Riecke.        Fully abstract translations between functional lan-
               guages.     Mathematical Structures in Computer Science,       3(4):387415,
               1993.

[Sim06]        Carlos Simpson. Explaining Gabriel-Zisman Localization to the Com-
               puter.   J. Autom. Reason.,       36:259285, April 2006.
      +
[SNO 10]       Peter Sewell, Francesco Zappa Nardelli, Scott Owens, Gilles Peskine,
               Thomas Ridge, Susmit Sarkar, and Rok Strnisa. Ott: Eective tool
               support for the working semanticist.        J. Funct. Program., 20(1):71122,
               2010.

[SO08]         Matthieu Sozeau and Nicolas Oury.             First-Class Type Classes.   In
               César Muñoz Otmane Ait Mohamed and Soène Tahar, editors,     The-
               orem Proving in Higher Order Logics, 21th International Conference,
               volume 5170 of Lecture Notes in Computer Science, pages 278293.
               Springer, August 2008.

[SvdW11]       Bas Spitters and Eelis van der Weegen. Type classes for mathemat-
               ics in type theory.        Mathematical Structures in Computer Science,
               21(4):795825, 2011.

[The10]        The Coq Development Team.     The Coq Proof Assistant Reference Man-
               ual  Version V8.3,        http://coq.inria.fr.
                                        2010.

[TvD88]        A. S. Troelstra and D. van Dalen. Constructivism in Mathematics: an
               Introduction, volume I and II. NorthHolland, Amsterdam, 1988.
[Ven00]        Varmo Vene. Categorical programming with inductive and coinductive
               types. PhD thesis, University of Tartu, 2000.
Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
                                Initiality for Typed Syntax and Semantics        ·     155




[Zsi10]   Julianna Zsidó.  Typed Abstract Syntax. PhD thesis, University of Nice,
          France, 2010.   http://tel.archives-ouvertes.fr/tel-00535944/.




                                       Journal of Formalized Reasoning Vol. 8, No. 2, 2015.
