Universal Algebra in UniMath
UUniversal Algebra in UniMath
Gianluca Amato ! ˇ Università di Chieti–Pescara, Italy
Marco Maggesi ! ˇ Università di Firenze, Italy
Cosimo Perini Brogi ! ˇ Università di Genova, Italy
Abstract
We present recent updates in our development of a library for Universal Algebra in the UniMathproof assistant. The code here discussed concerns multi-sorted signatures and their algebras, alongwith the basics for equation systems. Moreover, we give neat constructions of the correspondingunivalent categories by using the formalism of displayed categories, and show that the term algebraover a signature is the initial object of the category.Besides the formalization, we reflect on the methodological principles – based on the idea ofevaluability of our elementary construction by the built-in normalization procedure of the system –leading our coding style, and show that this path is practicable indeed by sketching simple examples.
Theory of computation → Algebraic language theory; Theory ofcomputation → Type theory; Theory of computation → Automated reasoning; Theory of computation → Constructive mathematics
Keywords and phrases
Universal Algebra, Homotopy Type Theory, Univalent Foundations, UniMath
Supplementary Material
Computer formalization in the UniMath system.
Version 2021-02-02 : https://github.com/amato-gianluca/UniMath/releases/tag/ITP2021 Funding
The authors thank the
European research network on types for programming and verific-ation (COST Action EUTypes CA15123) for supporting the School and Workshop on UnivalentMathematics 2019 where this project had its origin.
Gianluca Amato : Partially supported by INdAM-GNCS and COST Action EUTypes CA15123.
Marco Maggesi : Partially supported by the Italian Ministry of University and Research, INdAM-GNSAGA, and COST Action EUTypes CA15123.
Introduction
In this paper we report on our ongoing implementation of Universal Algebra within theformal environment of UniMath [15].Our leading motivation has been to provide a general framework for formalizing andstudying algebraic structures as presented in the field of Universal Algebra within a proofassistant. By providing a formal system for isolating the invariants of the theory we areinterested in, Univalent Mathematics has seemed to provide a suitable environment to carryout our endeavour since the very beginning. In particular, since it is natural to studymathematical structures up to isomorphisms, Univalent Mathematics seems to be especiallysuited for this kind of task.We chose to work within the UniMath environment since it provides a minimalistimplementation of univalent type theory, and, at the same time, it comes with a largerepository of mechanized results covering several fields of mathematics, so that it opens awide range of possibilities for future development of our formalization.By the code we survey on in the present paper, we have introduced the main notionsconcerning multi-sorted signatures. Developing them in a formal environment has required a r X i v : . [ c s . L O ] F e b Universal Algebra in UniMath some expedients in the definitions of the basics, and, accordingly, of some subsequentconstructions too. In particular, we had to introduce heterogeneous vectors and generalisetypes involving signatures by introducing (what we called) “sorted sets”.Having signatures, we then have given the related formalization of the category of algebrasusing the notion of a displayed category [6] over the category of sorted hSets, whose univalenceis proven by adapting the strategy used for the univalence of functor categories. The resultingconstruction is still a modular one and the resulting proof-term is more concise, for sure,than the one obtained by checking that algebras and homomorphisms satisfy the axioms forstandard categories.Defining terms is made complex by the fact that, by precise choice, UniMath does notmake use of the theory of (Co)Inductive Constructions. Therefore, we encode terms as listsof operation symbols, to be thought of as instructions for a stack-based machine. Terms arethose lists of symbols that may be virtually executed without generating type errors or stackunderflows.Moreover, we prove that the term algebra over a signature is the initial object in thecorresponding category, and that, more generally, an algebra of terms over a signature and aset of variables has the desired universal mapping property.Our formalization also includes the notion of equations and of algebras modelling anequation system associated with a signature; as for the category of algebras, we use thedisplayed category formalism to construct the univalent category of equational algebras overa given signature σ as the full subcategory of algebras over σ satisfying an equation system.A preliminary version of this work – with single-sorted signatures – has been presentedat the Workshop on Homotopy Type Theory and Univalent Mathematics 2020 [9]. Outline
In the main body of the present work, we will discuss all the notions we introduced in ourimplementation, so that the paper is structured as a presentation of the code, followed by thediscussion of some examples, a quick anticipation of future work and a brief comparison withdifferent formalizations of similar topics as coda. In details, we can summarise it as follows:In § 1, we give a general account of the methodology and the principles which guide ourwork;In § 2.1, we introduce the very basics of universal algebra along with some auxiliarydefinitions involving the new types we need to handle multi-sorted signatures , their algebras , and homomorphisms ;In § 2.2, we present the main details of our implementation of terms , prove that termalgebras and free algebras do have the required universal property – stated as thecontractibility of the type of out-going homomorphisms – and discuss the practical andmethodological relevance of our induction principle on terms;In § 2.3, we introduce systems of equations and equational algebras over a signature;In § 2.4, we sketch the main lines of our constructions of the categories of algebrasand equational algebras over a signature in terms of displayed categories over a basecategory of indexed hSets whose univalence is proven by a proof-strategy very close tothat one adopted for functor categories;Finally, § 3 is devoted to three applications of our implementation, namely: lists (§ 3.1),monoids (§ 3.2), and Tarski’s semantics of propositional boolean formulas (§ 3.3). . Amato and M. Maggesi and C. Perini Brogi 3
What we have mechanized is not, clearly, a mathematical novelty, but our endeavour hassome payoffs.Firstly, the code introduces in the UniMath library a minimal set of definitions andresults that is open to the community of developers for future achievements and formalinvestigations on the relation between pre-categorical research in general algebraic structuresand its subsequent development in e.g. Lawvere theories [1].Secondly, a peculiar feature of our code is the original implementation of term algebrasover a signature, which fits within the original approach to mechanization of univalentmathematics, but highlights the computational relevance of the constructions avoiding therestrictions imposed on the Coq engine in UniMath.As a matter of fact, terms for a signature constitute a family inductively defined overthe operation symbols together with an additional set of variables. As it is known, how-ever, UniMath makes use of just some features of the Coq proof assistant. To be precise,both record and inductive types are avoided in order to keep the system sound from afoundational/philosophical viewpoint.On the other hand, one of our main goals has been to make all our constructions aboutterms evaluable – as far as possible – by the built-in automation mechanisms of the proofassistant. More precisely, we represent each term using a sequence of function symbols.This sequence is thought to be executed by a stack machine: each symbol of arity n pops n elements from the stack and pushes a new element at the top. A term is denoted by asequence of function symbols that a stack-like machine can execute without type errors andstack underflow, returning a stack with a single element.This approach led us to prove both a recursion and induction principle on terms thatis evaluable as a functional term of the formal system. This is somehow mandatory whensticking to a form of (small scale) reflection: with our formalized stack-machine we havewritten in UniMath an implicit algorithm to compute terms over a signature; by meansof our induction principle we can run it – so to speak – within the very formal system ofUniMath, and use it to reason about terms in a safe way.Moreover, our methodology sympathizes (in a sense) with what Barendregt called Poincaréprinciple: our implementation of terms allows us to rely on the very core engine of UniMathwhen dealing with these formal objects, so that whenever we want to handle them we canfocus on the real demonstrative contents of the formalization, leaving to the automationbehind the computer proof assistant the trivial computational steps involved in the veryproof-term.Generally speaking, we find standard categorical presentations, though perspicaciouslyelegant in their abstractness, lacking a certain suitability for computerized mathematics.By contrast, our goal is justified by a specific need of methodological coherence – we justsketched it few line above – when approaching a work in formalization. Having proof-termsthat the computational machinery of UniMath practically evaluates as a correctly typedfunction seems to fit the philosophy and aims of the mechanization of mathematics betterthan just giving a formal counterpart of traditional mathematical notions that the computercannot handle feasibly. Formalization
Definitions and results we discuss in the present work are labelled with their correspondingproof-term identifiers in the formalization files. To improve readability, in what follows, most
Universal Algebra in UniMath
DecSet MaybeMoreListsHvectors Vectors ListSortedTypes SignaturesAlgebras TermsVTermsTermAlgebrasFreeAlgebrasCategory ofEqAlgebras EquationsEqAlgebrasCategory ofAlgebras
Figure 1
Intermodule dependencies of the Universal Algebra formalization in UniMath. proofs and technicalities are omitted, still they are available in our repository.Our code is freely accessible from https://github.com/amato-gianluca/UniMath andit has already been submitted for inclusion in the official UniMath repository. The revisiondiscussed in this paper is tagged as
ITP2021 . Our implementation consists of the files in thedirectories
UniMath/Algebra/Universal_Algebra for the basics of Universal Algebra (togetherwith auxiliary definitions and results), and
UniMath/CategoryTheory/categories/Universal_Algebra for the categories of algeb-ras and equational algebras over a signature.In order to help readers to browse our library, we summarise the dependencies between thefiles by the diagram in Figure 1 – where an arrow pointing to a node indicate the dependencyof the target from the source.
In the following subsections we present and comment on the main constructions constitutingour library. As anticipated, in the present work we want to make the code contained in theformalization files easily readable, so that we privilege a certain clarity of exposition over its . Amato and M. Maggesi and C. Perini Brogi 5 exhaustiveness. The interested reader can fill in the details by browsing the related files wemention during the discussion.
We start by defining a multi-sorted signature to be made of a decidable set of sorts alongwith operations classified by arities and result sorts, as in standard practice
Definition signature : UU := ∑ (S: decSet) (O: hSet), O → list S × S. The three natural projections associated to signatures are named sort , names , and ar Definition sorts ( σ : signature) := pr1 σ .Definition names ( σ : signature) := pr12 σ .Definition ar ( σ : signature) := pr22 σ . We also add specific projections for arities
Definition sort { σ : signature} (nm: names σ ) : sorts σ := pr2 (ar σ nm).Definition arity { σ : signature} (nm: names σ ) : list (sorts σ ) := pr1 (ar σ nm). These simple definitions rely on two files in
UniMath/Combinatorics , namely
Vectors.v and
Lists.v . We change these libraries in two aspects. First of all, we redefine lists in termsof the new datatype vec instead of using the ad-hoc type iterprod in the standard versionof the file. Moreover, we change a couple of theorems from opaque (
Qed. conclusion) totransparent (
Defined. conclusion). The latter changes are needed to make terms compute correctly.Note that, in a signature, the set of sorts should be a decSet : this is a type whoseequality is decidable, as defined in the file
DecSet.v . We need this extra property because –as we previously stated – we want to evaluate terms in the UniMath engine: we can achievethat by pushing sorts into a stack, and we need to check that the very stack contains certainsequences of sorts before applying an operator symbol. Note that a decSet also enjoys thedefining property of an hSet. Operators are only required to be in hSet .A signature may be alternatively specified through the type signature_simple . In asimple signature, the types for sorts and operation symbols are standard finite sets, and themap from operations symbols to domain and range is replaced by a list. In this way, thedefinition of a new signature is made simpler.
Definition signature_simple : UU := ∑ (ns: nat), list (list ( (cid:74) ns (cid:75) ) × (cid:74) ns (cid:75) ).Definition make_signature_simple {ns: nat} (ar: list (list ( (cid:74) ns (cid:75) ) × (cid:74) ns (cid:75) )): signature_simple := ns ,, ar.Coercion signature_simple_compile ( σ : signature_simple) : signature:= make_signature ( (cid:74) pr1 σ (cid:75) ,, isdeceqstn _)(stnset (length (pr2 σ ))) (nth (pr2 σ )). Single-sorted signatures are then defined as special cases of signature_simple . Definition signature_simple_single_sorted : UU := list nat.Definition make_signature_simple_single_sorted (ar: list nat) :signature_simple_single_sorted := ar.
Universal Algebra in UniMath
Coercion signature_simple_single_sorted_compile( σ : signature_simple_single_sorted): signature:= make_signature_single_sorted (stnset (length σ )) (nth σ ). Moving to the file
Algebras.v , we define an algebra over a given signature σ to be, asusual, support sets indexed by sorts together with operations with appropriate sorts: Definition algebra ( σ : signature): UU:= ∑ A: shSet (sorts σ ), ∏ nm: names σ , A ⋆ (arity nm) → A (sort nm).Definition supportset { σ : signature} (A: algebra σ ) := pr1 A.Definition support { σ : signature} (A: algebra σ ): sUU (sorts σ ) := pr1 A.Definition ops { σ : signature} (A: algebra σ ) := pr2 A.Definition dom { σ : signature} (A: algebra σ ) (nm: names σ ): UU := A ⋆ (arity nm).Definition rng { σ : signature} (A: algebra σ ) (nm: names σ ): UU:= support A (sort nm). We declare the projections supportset , support , and ops as type coercions. Moreover,as for signatures, we simplify the building term for algebras when starting from a simplesignature: Definition make_algebra_simple( σ : signature_simple) (A: Vector hSet (pr1 σ ))(ops: ( λ a, (el A) ⋆ (dirprod_pr1 a) → el A (dirprod_pr2 a)) ⋆ (pr2 σ )): algebra σ . A similar proof-term ( make_algebra_simple_single_sorted ) is given for single-sortedsignatures. As you can see, these definitions rely on many different notions and notations.These are introduced in
MoreLists.v , SortedTypes.v and
HVectors.v files.The file
MoreLists.v contains notations for lists, such as [v1; ...; vn] for list literalsand :: for cons , together with additional properties which cannot be found in the standardlibrary.The type hvec in HVectors.v denotes heterogeneous vectors: if v is a vector of types U1 , U2 , ..., Un , then hvec v is the product type U1 × (U2 × ... × (Un × unit)) . Weintroduce several basic operations on heterogeneous vectors: often they have the same syntaxas the corresponding operations on plain vectors, and a name which begins with the prefix h . We also introduce notations for heterogeneous vectors, such as [(v1; ...; vn)] for aliteral and ::: for prefixing.Sorted types are types indexed by elements of another type (the index type), so thatan element of sUU S is an S -sorted type, i.e. an S -indexed family of types. Similarly, thetype shSet S is an S -indexed family of hSets. For functions, X s→ Y denotes the type of S -sorted mapping between X and Y , i.e. of S -indexed families of functions X s → Y s . Moreprominently, for any S -sorted type X , its lifting to list S is denoted by X ⋆ , and is ruledby the identity X [s1; s2; ...; sn] = [X s1 ; X s2 ; ... ; X sn] . Accordingly, if f is an indexed mapping between S -indexed types X and Y , then f ⋆⋆ is the lifting of f to a We need this type to handle operations taking inputs of different sorts. . Amato and M. Maggesi and C. Perini Brogi 7 list S -indexed mapping between X ⋆ and Y ⋆ . This operation ⋆⋆ is indeed functorial, andwe prove that in a form which does not require function extensionality, since resorting toaxioms would break computability of terms.All of these notions allow us to define algebra homomorphism : Definition ishom { σ : signature} {A1 A2: algebra σ } (h: A1 s→ A2) : UU:= ∏ (nm: names σ ) (x: dom A1 nm), h _ (A1 nm x) = A2 nm (h ⋆⋆ _ x).Definition hom { σ : signature} (A1 A2: algebra σ ): UU := ∑ (h: A1 s→ A2), ishom h. As expected, the property of being an homomorphism belongs to hProp , so that the type A1 (cid:148) A2 of homomorphisms between A1 and A2 is an hSet : Theorem isapropishom { σ : signature} {A1 A2: algebra σ } (f: sfun A1 A2): isaprop (ishom f).Theorem isasethom { σ : signature} (A1 A2: algebra σ ): isaset (A1 (cid:148) A2).
Next, we prove – by lemmas ishomid and ishomcomp – that the identity function determinesan identity homomorphism, and that the property ishom is closed under composition.
The file
Algebras.v is closed by the construction of the unit algebra as the final algebraamong those defined over a given signature:
Definition unitalgebra ( σ : signature): algebra σ := make_algebra (sunitset (sorts σ )) tosunit.Theorem iscontrhomstounit { σ : signature} (A: algebra σ ): iscontr (hom A (unitalgebra σ )). However, we are mostly interested in the initial object of the category of algebras, namelythe algebra of terms over a given signature. In standard textbooks, the set of terms over asignature σ and a (disjoint) set V of variables is defined as the least set including V andclosed under application of symbols of σ .For being inductive types unavailable in our formal system, we have developed a peculiardevice to implement that notion. In our formalization we start with the special case wherethe set of variables V is empty. The rough and general idea can be sketched as follows: A sequence of function symbols is thought of as a series of commands to be executed bya stack machine whose stack is made of sorts, and which we define by means of a maybemonad we construct from raw in
Monad.v : Local Definition oplist ( σ : signature):= list (names σ ).Local Definition stack ( σ : signature): UU := maybe (list (sorts σ )). When an operation symbol is executed, its arity is popped out from the stack and replacedby its range. When a stack underflow occurs, or when the sorts present in the stackare not the ones expected by the operator, the stack goes into an error condition whichis propagated by successive operations. We implement this process by means of twofunctions: opexec and oplistexec : Universal Algebra in UniMath
Local Definition opexec (nm: names σ ): stack σ → stack σ := flatmap ( λ ss, just (sort nm :: ss)) ◦ flatmap ( λ ss, prefix_remove (arity nm) ss).Local Definition oplistexec (l: oplist σ ): stack σ := foldr opexec (just []) l. The former is the stack transformation corresponding to the execution of the operationsymbol nm . The latter returns the stack corresponding to the execution of the entire oplist l starting from the empty stack. The list is executed from the last to the firstoperation symbol.Several additional lemmas are required in order to make us able to handle stacks – byconcatenating, splitting, etc. – without incurring failures breaking down the whole process,as defined in Terms.v . Finally, we define a term to be just a list of operation symbols that, after being executedby oplistexec , returns a list of length one with appropriate sort: Local Definition isaterm (s: sorts σ ) (l: oplist σ ): UU:= oplistexec l = just ([s]).Local Definition term ( σ : signature) (s: sorts σ ): UU:= ∑ t: oplist σ , isaterm s t. Terms may be built using the build_term constructor and decomposed trough the princop and subterms accessors:
Local Definition build_term (nm: names σ ) (v: (term σ ) ⋆ (arity nm)):term σ (sort nm).Definition princop {s: sorts σ } (t: term σ s): names σ .Definition subterms {s: sorts σ } (t: term σ s): (term σ ) ⋆ . The implementation function build_term is quite straightforward: it concatenates nm andthe oplists underlying the terms in v , and builds a proof that the resulting oplist is a termfrom the proofs that the elements of v are terms. The princop and subterms accessorsare projections of a more complex operation called term_decompose which breaks a termin principal operation symbols nm and subterms v , and, at the same time, provides theproof-terms that characterize their behaviour. At this point, we proceed in proving induction over terms. The inductive hypothesis, beingquite complex, is stated in the term_ind_HP type.
Definition term_ind_HP (P: ∏ (s: sorts σ ), term σ s → UU) : UU:= ∏ (nm: names σ ) (v: (term σ ) ⋆ (arity nm)) (IH: hvec (h1map_vector P v)), P (sort nm) (build_term nm v). In particular, since we need to decide when a stack is correctly executed and when an underflow occurs,we see the reasons for choosing sorts to constitute a decidable set. From a purely HoTT-perspective, we can easily see also that the type of stacks over σ is an hSet, sothat the property of being a term is not proof-relevant ( isapropisaterm ). . Amato and M. Maggesi and C. Perini Brogi 9 Given a family P of types, indexed by a sort s and a term over s , the inductive hypothesisis a function that, given an operation symbol nm , a sequence of terms v , and a sequence ofproofs of P for all terms in v , is able to build a proof of P for the term build_term nm v ,i.e., nm ( v , . . . , v n ) . The identifier h1map_vector simply denotes the variant of map forheterogeneous vectors. Given this auxiliary definition, the induction principle for terms maybe easily stated as follows: Theorem term_ind (P: ∏ (s: sorts σ ), term σ s → UU) (R: term_ind_HP P){s: sorts σ } (t: term σ s): P s t. The proof proceeds by induction on the length of the oplist underlying t , using the term_ind_onlength auxiliary function.Simple examples of use of the induction principle on terms are the depth and fromterm functions. The former computes the depth of a term, and the latter is essentially theevaluation map for ground terms in an algebra. Local Definition fromterm {A: sUU (sorts σ )}(op : ∏ (nm : names σ ), A ⋆ (arity nm) → A (sort nm)){s: sorts σ }: term σ s → A s:= term_ind ( λ s _, A s) ( λ nm v rec, op nm (h2lower rec)). The h2lower proof-term which appears in the definition of fromterm is just a technicalityneeded to convert between types which are provably equal but not convertible. This mightbe replaced by a transport, if we were not interested in computability. The same can be saidfor the proof term h1lift , later in the definition of term_ind .In order to reason effectively on inductive definition, we need an induction unfolding prop-erty. For natural numbers, it is nat_rect P a IH (S n) = IH n (nat_rect P a IH n) ,which means that the result of applying the recursive definition to
S n may be obtained byapplying the recursive definition to n and then the inductive hypothesis. While this inductionunfolding properties are provable just by reflexivity for many inductive types, this doesnot hold for terms, and a quite complex proof is needed: Lemma term_ind_step (P: ∏ (s: sorts σ ), term σ s → UU) (R: term_ind_HP P)(nm: names σ ) (v: (term σ ) ⋆ (arity nm)): term_ind P R (build_term nm v)= R nm v (h2map ( λ s t q, term_ind P R t) (h1lift v)). Many of the definition which appears in
Terms.v are declared as
Local . This is becausethey are considered internal implementation details and should not be used if not explicitlyneeded. In particular, this holds for a set of identifiers that will be redefined in
VTerms.v to work on terms with variables. Since sometimes it may be convenient to have specializedfunctions that only work with ground terms, they are exported through a series of notations,such as:
Notation gterm := term.Notation build_gterm := build_term.
Considering terms with variables is what we do in file
VTerms.v . The idea is that a termwith variables in V over a signature σ is a ground term in a new signature where constantsymbols are enlarged with the variables in V . Variables and corresponding sorts are declaredin a varspec ( variable specification ), while vsignature builds the new signature. Definition varspec ( σ : signature) := ∑ V: hSet, V → sorts σ .Definition vsignature ( σ : signature) (V: varspec σ ): signature:= make_signature (sorts σ ) (setcoprod (names σ ) V)(sumofmaps (ar σ ) ( λ v, nil ,, varsort v)). The proof-terms namelift and varname are the injections of, respectively, operation sysmbolsand variables in the extended signature.
Definition namelift (V: varspec σ ) (nm: names σ ): names (vsignature σ V):= inl nm.Definition varname {V: varspec σ } (v: V): names (vsignature σ V) := inr v.
Then, a list of definitions comes: they essentially introduce terms with variables by resortingto ground terms.
Definition term ( σ : signature) (V: varspec σ ): sUU (sorts σ ) := gterm (vsignature σ V).Definition build_term {V: varspec σ } (nm: names σ ) (v: (term σ V) ⋆ (arity nm)): term σ V (sort nm) := build_gterm (namelift V nm) v.Definition varterm {V: varspec σ } (v: V): term σ V (varsort v) := build_gterm (varname v) [()].
Finally, in
FreeAlgebras.v we pack terms and the build_term operation into the algebra T σ ( V ) of terms over a given signature σ and set of variables V . For this algebra, we provethe universal property. Definition free_algebra ( σ : signature) (V: varspec σ ): algebra σ :=@make_algebra σ (termset σ V) build_term.Definition universalmap: ∑ h: free_algebra σ V (cid:148) a, ∏ v: V, h _ (varterm v) = α v.Definition iscontr_universalmap: iscontr ( ∑ h:free_algebra σ V (cid:148) a, ∏ v:V, h (varsort v) (varterm v) = α v). In TermAlgebras.v we just consider the special case of
FreeAlgebras.v for the empty setof variables, i.e., for ground terms. In this case, the universal mapping property is replacedby the initiality of the ground term algebra.
Equations and their associated structures are key notions in Universal Algebra. Althoughan extensive treatment of notions such as equational algebra and variety is out of the scopeof the present work, the basic definitions are already present in our implementation in file
EqAlgebras.v .In our setting, an equation is a pair of terms (with variables) of the same sort. Theirintended meaning is to specify identities law where variables are implicitly universallyquantified.
Definition equation ( σ : signature) (V: varspec σ ): UU:= ∑ s: sorts σ , term σ V s × term σ V s. . Amato and M. Maggesi and C. Perini Brogi 11
The associated projections are denoted eqsort , lhs , and rhs respectively. An equationsystem is just a family of equations. Definition eqsystem ( σ : signature) (V: varspec σ ): UU:= ∑ E : UU, E → equation σ V. Then, we pack all the above data into an equational specification , that is a signature endowedwith an equation system (and the necessary variable specification).
Definition eqspec: UU := ∑ ( σ : signature) (V: varspec σ ), eqsystem σ V. The interpretation of an equation is easily defined using function fromterm introduced in§ 2.2.1. More precisely, the predicate holds that checks if the universal closure of an equation e holds in an algebra a is given as follows: Definition holds { σ : signature} {V: varspec σ }(a: algebra σ ) (e: equation σ V) : UU:= ∏ α , fromterm a α (eqsort e) (lhs e) = fromterm a α (eqsort e) (rhs e). From this, it is immediate to define the type eqalgebra of equational algebras as thosealgebras in which all the equations of a given equational specification hold. Universal algebra has a natural and fruitful interplay with category theory [12]. As claimedin the introduction, our mechanization includes basic categorical constructions for organizingand reasoning about universal algebra structures. In agreement with the general philosophyof univalent mathematics, we can prove that the categories we are interested in – of algebrasand equational algebras – are univalent indeed.In order to develop formal proofs of that property, two possible strategies are available.A simplest one consists of building the desired categories from scratch, and then provethat univalence holds between their isomorphic objects. However, experience has shownthat this strategy often lacks a certain naturalness, and it makes the steps involved in theconstruction hard.The second available strategy has revealed practicable in a more efficient way: we definethe desired category in a step-by-step construction by adding layers to a base category already given. Such a notion of layer corresponds precisely to a displayed category [6]:displayed categories are type-theoretic counterpart of fibrations and constitute a widelyadopted instrument to reason about categories even at higher dimensions [2] in the UniMathlibrary.After defining a displayed category over a base category, we can then build a total category whose univalence is proven by checking univalence for the base category and a displayedversion of univalence for the category displayed over the base. This is a generalised versionof the so-called structure identity principle as introduced first by Aczel as invariance of allstructural properties of isomorphic structures (broadly considered).To build our category of algebras, we apply just this very principle: the structure ofalgebras and homomorphisms is displayed over a base category of shSets that we constructfrom raw.At this point, we can easily prove the displayed univalence for that layer, whereas provingthat the base category of shSets is univalent revealed already non-trivial. We managed on See the remarks in [5], where category theory was introduced first in a HoTT-setting. the issue by tweaking the proof-terms already constructed for functor categories in UniMath.The resulting total category of algebras is therefore univalent in the usual sense.Turning now to equational algebras, we do not have to start the construction againfrom scratch: within the displayed category formalism we can identify the “substructure”of algebras over shSets satisfying a system of equations. In other terms, we can take forequational algebras the layer over the category of shSets made of the full displayed subcategory of the displayed category of algebras identified by the type is_eqalgebra . Again, provingdisplayed univalence for this layer is not difficult, so that the total category of equationalalgebras over a system of equations is univalent, as required.Finally, we rephrase the universal property of the term algebra shown in § 2.2: we canstate its initiality in the category of algebras over a given σ by means of the proof-term madeof the of the algebra itself and the contractibility of out-going homomorphisms, previouslyconstructed. In this section, we want to illustrate by simple examples how to use our framework in threedifferent settings.
We start with a very simple multi-sorted example, the signature of the list datatype and itsalgebras. We will show how to specify a signature in our framework and how to interpreta list datatype as an algebra. The code for this example can be found in the module
UniMath.Algebra.Universal.Examples.ListDataType .We will need two sorts, one for elements and the other for lists. Correspondingly, wename the two elements • and • of the standard finite set with two elements (cid:74) (cid:75) . Definition elem_sort_idx: (cid:74) (cid:75) := • (cid:74) (cid:75) := • Our signature for the language of lists will consist of two operation symbols for the usualconstructors nil and cons respectively. Such a signature is encoded with a list of pairs.Each pair describe the input (a list of sorts) and the output (a sort) for the correspondingconstructor.
Definition list_signature: signature_simple:= make_signature_simple[ ( nil ,, list_sort_idx ) ;( [elem_sort_idx ; list_sort_idx] ,, list_sort_idx ) ]%list.
For enhanced readability, we assign explicit names to the operator symbols.
Definition nil_idx: names list_signature := • • Now, we can endow the list datatype of UniMath ( listset ) with the structure of an algebraover list_signature by using the list constructors nil and const . We fix a type A for ourelements. Variable A : hSet.
Then, the class of algebras over list_signature is given by . Amato and M. Maggesi and C. Perini Brogi 13
Definition list_algebra := make_algebra_simple list_signature[( A ; listset A )][( λ _, nil ; λ p, cons (pr1 p) (pr12 p) )]. From now on in this section, lemmas are just simple verification of convertibility. They areall proven by reflexivity and the proof scripts are omitted. To begin with, we check that thesort of elements is A and the sort of lists is given by the associated list datatype: Lemma elem_sort_id : supportset list_algebra elem_sort_idx = A.Lemma list_sort_id : supportset list_algebra list_sort_idx = listset A.
Next, define the associated algebra constructors. First, let us consider consider the emptylist constructor.
Definition list_nil : listset A := ops list_algebra nil_idx tt.
As expected, it reduces to the usual nil constructor.
Lemma list_nil_id : list_nil = @nil A.
For the list cons constructor, the situation is more complicated. The domain of the constructoris the product
A × listset A × unit , meaning that the constructor has two (uncurried)arguments
Lemma list_cons_dom_id : dom list_algebra cons_idx = A × listset A × unit.
Thus, the operation extracted by the ops projection has type with the following form
Definition list_cons : A × listset A × unit → listset A:= ops list_algebra cons_idx.
That said, our list_cons operation reduces to the usual list cons.
Lemma list_cons_id (x: A) (l: listset A) : list_cons (x,, (l,, tt)) = cons x l.
From now on, we will consider single sorted examples for the sake of simplicity. In thisSection, we will discuss the eqalgebra of monoids. The code for this example can be foundin the module
UniMath.Algebra.Universal.Examples.Monoid .To define single sorted signatures, our function make_signature_simple_single_sorted is a handy shorthand (previously introduced) that takes a list of natural numbers.
Definition monoid_signature := make_signature_simple_single_sorted [2; 0].
Monoids are already defined in UniMath. Similarly to what we did in the previous sectionwith lists, we endow monoids with the structure of a monoid algebra.
Definition monoid_algebra (M: monoid) : algebra monoid_signature:= make_algebra_simple_single_sorted monoid_signature M[( λ p, op (pr1 p) (pr12 p) ; λ _, unel M )]. Next, we provide a variable specification, i.e. an hSet of variables together with a map fromvariables to sorts. Since monoid_signature is single-sorted, the only available sort is tt .Then, we build the associated algebra of open terms that will be used to specify the equationsof the theory of monoids. Definition monoid_varspec : varspec monoid_signature:= make_varspec monoid_signature natset ( λ _, tt).Definition Mon : UU := term monoid_signature monoid_varspec tt.Definition mul : Mon → Mon → Mon := build_term_curried ( •
0: names monoid_signature).Definition id : Mon := build_term_curried ( •
1: names monoid_signature).
Term variables are associated to natural numebers. In this case, three variables x , y , z willsuffice for our needs Definition x : Mon := varterm (0: monoid_varspec).Definition y : Mon := varterm (1: monoid_varspec).Definition z : Mon := varterm (2: monoid_varspec).
Now, we have all the ingredients to specify our equations: the monoid axioms of associativity,left identity, and right identity.
Definition monoid_equation : UU := equation monoid_signature monoid_varspec.Definition monoid_mul_lid : monoid_equation := tt,, make_dirprod (mul id x) x.Definition monoid_mul_rid : monoid_equation := tt,, make_dirprod (mul x id) x.Definition monoid_mul_assoc : monoid_equation:= tt,, make_dirprod (mul (mul x y) z) (mul x (mul y z)).
We pack the above equations together into an equation system ( monoid_axioms ) and itsassociated equational specification ( monoid_eqspec ); finally, we define the class of equa-tional algebras of monoids monoid_eqalgebra . We omit the formal construction which isuncomplicated and reduces essentially to uninteresting bookkeeping.Next, we want to show that every “classical” monoid M has a natural structure ofequational algebra. We have two show that M is a model for our equation system. Let usbegin with the left-identity axiom Lemma holds_monoid_mul_lid : holds (monoid_algebra M) monoid_mul_lid.Proof.intro α . cbn in α .change (fromterm (monoid_algebra M) α tt (mul id x) = α α
0) = α As you see, we fix the variable evaluation α , then we observe that our goal reduces to thesame law expressed in the usual language of monoids – op for the product, unel M for theidentity, α for the first variable x – and then the goal is solved at once by applying thecorresponding monoid axiom lunax .The other two laws (for right identity and associativity) are proven in the same way. Wecan now pack everything into a monoid eqalgebra (definitions is_eqalgebra_monoid and make_monoid_eqalgebra . We now describe a further example based on a simple single sorted algebraic language: thealgebra of booleans, and its connectives. The code for this example can be found in themodule
UniMath.Algebra.Universal.Examples.Bool . We consider a language with theusual boolean connectives and constants: truth, falsity, negation, conjunction, disjunction,and implication.Arities can be specified simply by naturals (the number of arguments). We use the function make_signature_simple_single_sorted to build a signature from the list of arities: . Amato and M. Maggesi and C. Perini Brogi 15
Definition bool_signature :=make_signature_simple_single_sorted [0; 0; 1; 2; 2; 2].
Obviously, the type of booleans is already defined in UniMath, together with its usualconstants and operations: false , true , negb , andb , orb , implb . Booleans forms an hSetwhich is denoted boolset . It is easy to organize these constituents into an algebra for oursignature by specifying the translation: Definition bool_algebra :=make_algebra_simple_single_sorted bool_signature boolset[( λ _, false ; λ _, true ; λ x, negb (pr1 x) ; λ x, andb (pr1 x) (pr12 x) ; λ x, orb (pr1 x) (pr12 x) ; λ x, implb (pr1 x) (pr12 x) )]. Next, we build the algebra of (open) terms, that is, boolean formulae. This is done in twosteps. First, we give a variable specification, i.e. a set of type variables:
Definition bool_varspec := make_varspec bool_signature natset ( λ _, tt). Then, we define the algebra of terms and the associated constructors.
Definition T := term bool_signature bool_varspec tt.Definition bot : T := build_term_curried ( • • • • • • Finally, we use the universal property of the term algebra to define the interpretation ofboolean formulae:
Definition interp ( α : assignment bool_algebra bool_varspec) (t: T) : bool :=fromterm (ops bool_algebra) α tt t. At this point, we can check the effectiveness of our definitions with some applications. Toformulate our tests, we introduce three variables x , y , z – as done in the previous section –and a simple evaluation function v for variables that assigns true to the variable x and y (the variable of index 0 and 1) and false otherwise.Now, we can run the interpretation function by using the Coq internal evaluationmechanism (using the vernacular command Eval strategy in term ). For instance, theevaluation of the formula x ∧ ( z → ¬ y ) becomes: Eval lazy ininterp ( λ n, match n with 0 => true | 1 => true | _ => false end)(conj x (impl z (not y)). Note that the choice of the lazy strategy is not accidental. Computations required to evaluatesuch a proof terms are quite heavy and the standard call by value strategy does not seemsable to produce a result in reasonable time.A few other examples are available in our code as, for instance, a proof of Dummett’stautology:
Lemma Dummett : ∏ i, interp i (disj (impl x y) (impl y x)) = true.Proof.intro i. lazy.induction (i 0); induction (i 1); apply idpath.Qed. Notice that this formal proof is just a case analysis for truth-tables in disguise: weinstantiate the values of x and y by applying induction twice, but the remaining job isleft to the computing mechanism of Coq, which is able to autonomously verify that theevaluation does yield the value true in all cases – we only need to apply idpath . Conclusions and related works
By the code just surveyed, we covered most of fundamental concepts in Universal Algebra.We plan to enhance our implementation along three directions:First of all, to streamline the interface provided by the library. At this point, the user ofthe library is exposed to many technical details only relevant to the implementation, suchas: the internal signatures generated by vsignature for dealing with variables in terms; theexistence of two term algebras, one for ground terms, the other for general terms, while theformer should only be a particular case of the latter. We plan to redesign the interface in orderto hide the internal details as much as possible. Furthermore, the interface for heterogeneousvectors might be generalized to make the
HVectors module more useful outside of the scopeof our library.Next, to include more advanced results. On the one side, we plan to complete thetreatment of equational algebras by defining the initial algebra of terms modulo equationalcongruence. On the other side, we want to include some relevant theorems, such as thehomomorphism theorems and Birkhoff’s theorem for varieties.Finally, to extend the library with refined applications and examples of univalent reasoning.This would give evidence that even the minimalist environment of UniMath does allow itsuser to approach mechanized mathematics with the advantages of both univalent reasoning –to handle equivalent objects as naturally as in informal mathematics – and the automationprocess of the proof assistant – to be smartly used for performing “internal” implementationsin order to leave all computations with no demonstrative significance to the machine.Different approaches to the field in computerized mathematics are already known.A classical work on implementing Universal Algebra in dependent type theory is the oneof Capretta [10], where he systematically uses setoids in Coq to handle equality on structures.Another attempt, still based on setoids, has been recently carried on in Agda [11]. We sharethe feeling that Univalent Foundations provide a more principled approach.Initial semantics furnishes elegant techniques for studying induction and recursion prin-ciples in a general setting encompassing applications in programming languages and logic.Assuming univalence, steady research activity produced over the time a number of contribu-tions to the UniMath library, see e.g. [3, 4, 7, 8].Lynge’s [13] – still under development in [14] – seems to settle in a framework thatmore closely compares with ours. Despite both our formalization and Lynge’s one assumeUnivalent Mathematics as formal environment, the study we are proposing here differsfrom his one by adopting a more foundational perspective. This point of view materialisesin our choice of UniMath over CoqHoTT, which is the system adopted by Lynge for hisencoding. Moreover, our focus makes the implementation we are proposing different also fromcategorical treatments mentioned above because of the care we have taken about making theconstructions easily evaluable by the very normalization procedure of terms. . Amato and M. Maggesi and C. Perini Brogi 17
References Jiří Adámek, Jiří Rosick`y, and Enrico Maria Vitale.
Algebraic theories: a categorical introduc-tion to general algebra , volume 184. Cambridge University Press, 2010. Benedikt Ahrens, Dan Frumin, Marco Maggesi, and Niels van der Weide. Bicategoriesin Univalent Foundations. In Herman Geuvers, editor, , volume 131 of
LeibnizInternational Proceedings in Informatics (LIPIcs) , pages 5:1–5:17, Dagstuhl, Germany, 2019.Schloss Dagstuhl–Leibniz-Zentrum fuer Informatik. URL: http://drops.dagstuhl.de/opus/volltexte/2019/10512 , doi:10.4230/LIPIcs.FSCD.2019.5 . Benedikt Ahrens, André Hirschowitz, Ambroise Lafont, and Marco Maggesi. High-Level Signa-tures and Initial Semantics. In Dan Ghica and Achim Jung, editors, , volume 119 of
Leibniz International Proceedingsin Informatics (LIPIcs) , pages 4:1–4:22, Dagstuhl, Germany, 2018. Schloss Dagstuhl–Leibniz-Zentrum fuer Informatik. URL: http://drops.dagstuhl.de/opus/volltexte/2018/9671 , doi:10.4230/LIPIcs.CSL.2018.4 . Benedikt Ahrens, André Hirschowitz, Ambroise Lafont, and Marco Maggesi. Modular Spe-cification of Monads Through Higher-Order Presentations. In Herman Geuvers, editor, ,volume 131 of
Leibniz International Proceedings in Informatics (LIPIcs) , pages 6:1–6:19,Dagstuhl, Germany, 2019. Schloss Dagstuhl–Leibniz-Zentrum fuer Informatik. URL: http://drops.dagstuhl.de/opus/volltexte/2019/10513 , doi:10.4230/LIPIcs.FSCD.2019.6 . Benedikt Ahrens, Krzysztof Kapulkin, and Michael Shulman. Univalent categories and therezk completion. In Maria del Mar González, Paul C. Yang, Nicola Gambino, and JoachimKock, editors,
Extended Abstracts Fall 2013 , pages 75–76, Cham, 2015. Springer InternationalPublishing. Benedikt Ahrens and Peter LeFanu Lumsdaine. Displayed Categories.
Logical Methods inComputer Science , Volume 15, Issue 1, March 2019. URL: https://lmcs.episciences.org/5252 , doi:10.23638/LMCS-15(1:20)2019 . Benedikt Ahrens and Ralph Matthes. Heterogeneous Substitution Systems Revisited. In TarmoUustalu, editor, , volume 69 of
Leibniz International Proceedings in Informatics (LIPIcs) , pages 2:1–2:23,Dagstuhl, Germany, 2018. Schloss Dagstuhl–Leibniz-Zentrum fuer Informatik. URL: http://drops.dagstuhl.de/opus/volltexte/2018/8472 , doi:10.4230/LIPIcs.TYPES.2015.2 . Benedikt Ahrens and Anders Mörtberg. Some wellfounded trees in unimath. In Gert-MartinGreuel, Thorsten Koch, Peter Paule, and Andrew Sommese, editors,
Mathematical Software –ICMS 2016 , pages 9–17, Cham, 2016. Springer International Publishing. Gianluca Amato, Marco Maggesi, Maurizio Parton, and Cosimo Perini Brogi. Universal Algebrain UniMath. In
Workshop on Homotopy Type Theory/Univalent Foundations – HoTT/UF2020 ,2020. URL: https://hott-uf.github.io/2020/ . Venanzio Capretta. Universal algebra in type theory. In Yves Bertot, Gilles Dowek, AndréHirschowits, Christine Paulin, and Laurent Théry, editors,
Theorem Proving in Higher OrderLogics, 12th International Conference, TPHOLs ’99 , volume 1690 of
LNCS , pages 131–148.Springer, 1999. URL: . Emmanuel Gunther, Alejandro Gadea, and Miguel Pagano. Formalization of universal algebrain Agda.
Electronic Notes in Theoretical Computer Science , 338:147–166, 2018. URL: . Martin Hyland and John Power. The category theoretic understanding of universal algebra:Lawvere theories and monads.
Electronic Notes in Theoretical Computer Science , 172:437–458,2007. Andreas Lynge. Universal algebra in HoTT, 2017. Bachelor’s thesis, Department of Math-ematics, Aarhus University. URL: https://github.com/andreaslyn/Work/blob/master/Math-Bachelor.pdf . Andreas Lynge and Bas Spitters. Universal algebra in HoTT. In
TYPES 2019, 25th Inter-national Conference on Types for Proofs and Programs , 2019. URL: . Vladimir Voevodsky, Benedikt Ahrens, Daniel Grayson, et al. UniMath — a computer-checkedlibrary of univalent mathematics. Available at https://github.com/UniMath/UniMathhttps://github.com/UniMath/UniMath