# Es/Teoría de Categorías y Programación Funcional @ Stanford: Clase 1

**Aviso**: Esta página está en proceso de traducción.

This page now includes additional information based on the notes taken in class. Hopefully this will make the notes reasonably complete for everybody.

## Contents

## Bienvenida

El autor original es Mikael Vejdemo-Johansson. Se le puede encontrar en su oficina 383-BB durante horas de oficina o por correo en mik@math.stanford.edu.

## Introducción

### ¿Por qué este curso?

Las introducciones a Haskell usualmente incluyen indicaciones de que la Teoría de Categorías es una herramienta útil, aunque no haces mucho más que mencionarlo. El objetivo de este curso es cubrir esa brecha, y proporcionar una introducción a la Teoría de Categorías que se enlace con Haskell y con la programación funcional como fuente de ejemplos y aplicaciones.

### ¿Qué incluye?

La definición de categorías, objetos especiales y morfismos, functores, transformación natural, (co-)límites y casos específicos, adjuntos, libertad y presentación como construcciones categóricas, mónadas y flechas de Kleisli, recursión con construcciones categóricas. Maybe, just maybe, if we have enough time, we'll finish with looking at the definition of a topos, and how this encodes logic internal to a category. Applications to fuzzy sets.

### ¿Qué hace falta?

Los ejemplos provendrán de matemáticas discretas, lógica, programación en Haskell y álgebra lineal. Espero que los siguientes conceptos sean por lo menos vagamente familiares para alguien estudiando este curso:

- Conjuntos
- Funciones
- Permutaciones
- Grupos
- Conjuntos parcialmente ordenados
- Espacios vectoriales
- Mapas lineales
- Matrices
- Homomorfismos

### Buenas referencias

En la biblioteca de matemáticas/CC (Stanford) hay:

*Mac Lane*:**Categories for the working mathematician***Awodey*:**Category Theory**

### Monoids

Para establecer la notación y estar seguros de que todos hayan visto la definición:

**Definición** Un *monoide* es un conjunto equipado con una operación binaria asociativa (en Haskell: `mappend`

) y un elemento identidad (en Haskell: `mempty`

).

Un *semigrupo* es un monoide sin el requerimiento de elemento identidad.

Una función es un homomorfismo de monoide si se cumplen las siguientes condiciones:

## Categoría

### Gráficas

Recordemos la definición de *gráfica (dirigida)*. Una gráfica es una colección de *aristas (flechas)* y *vértices (nodos)*. A cada arista se le asigna un nodo *fuente* y un nodo *destino*.

Dado un grafo , denotamos la colección de nodos de y la colección de flechas por . Estas dos colecciones están conectados, y la gráfica dada su estructura, por dos funciones: la función de fuente y el objetivo de la función .

No deberemos, en general, necesitar de una de las colecciones para ser un conjunto, pero felizmente aceptamos grandes colecciones; tratar con la teoría de conjuntos paradojas como son y cuando tenemos que hacerlo. Un gráfo donde ambos nodos y flechas son conjuntos se llama "pequeño". Un grafo que contenga una clase se llama "Largo".

Si los dos y son finitos, el grafo se llama*finito*también.

The *empty graph* has .

A *discrete graph* has .

A *complete graph* has .

A *simple graph* has at most one arrow between each pair of nodes. Any relation on a set can be interpreted as a simple graph.

- Show some examples.

A *homomorphism* of graphs is a pair of functions and such that sources map to sources and targets map to targets, or in other words:

By a *path* in a graph from the node to the node of length , we mean a sequence of edges such that:

- for all other .

Paths with start and end point identical are called *closed*. For any node , there is a unique closed path starting and ending in of length 0.

For any edge , there is a unique path from to of length 1: .

We denote by the set of paths in of length .

### Categories

We now are ready to define a category. A *category* is a graph equipped with an associative composition operation , and an identity element for composition for each node of the graph.

Note that can be viewed as a subset of , the set of all pairs of arrows. It is intentional that we define the composition operator on only a subset of the set of all pairs of arrows - the composable pairs. Whenever you'd want to compose two arrows that don't line up to a path, you'll get nonsense, and so any statement about the composition operator has an implicit "whenever defined" attached to it.

The definition is not quite done yet - this composition operator, and the identity arrows both have a few rules to fulfill, and before I state these rules, there are some notation we need to cover.

#### Backwards!

If we have a path given by the arrows in , we expect and to compose to something that goes . The origin of all these ideas lies in geometry and algebra, and so the abstract arrows in a category are *supposed* to behave like functions under function composition, even though we don't say it explicitly.

Now, we are used to writing function application as - and possibly, from Haskell, as `f x`

. This way, the composition of two functions would read .

On the other hand, the way we write our paths, we'd read then . This juxtaposition makes one of the two ways we write things seem backwards. We can resolve it either by making our paths in the category go backwards, or by reversing how we write function application.

In the latter case, we'd write , say, for the application of to , and then write for the composition. It all ends up looking a lot like Reverse Polish Notation, and has its strengths, but feels unnatural to most. It does, however, have the benefit that we can write out function composition as and have everything still make sense in all notations.

In the former case, which is the most common in the field, we accept that paths as we read along the arrows and compositions look backwards, and so, if and , we write , remembering that *elements* are introduced from the right, and the functions have to consume the elements in the right order.

The existence of the identity map can be captured in a function language as well: it is the existence of a function .

Now for the remaining rules for composition. Whenever defined, we expect associativity - so that . Furthermore, we expect:

- Composition respects sources and targets, so that:

In a category, arrows are also called *morphisms*, and nodes are also called *objects*. This ties in with the algebraic roots of the field.

We denote by , or if is obvious from context, just , the set of all arrows from to . This is the *hom-set* or *set of morphisms*, and may also be denoted .

If a category is large or small or finite as a graph, it is called a large/small/finite category.

A category with objects a collection of sets and morphisms a selection from all possible set-valued functions such that the identity morphism for each object is a morphism, and composition in the category is just composition of functions is called *concrete*. Concrete categories form a very rich source of examples, though far from all categories are concrete.

### New Categories from old

As with most other algebraic objects, one essential part of our tool box is to take known objects and form new examples from them. This allows us generate a wealth of examples from the ones that shape our intuition.

Typical things to do here would be to talk about *subobjects*, *products* and *coproducts*, sometimes obvious *variations on the structure*, and what a *typical object* looks like. Remember from linear algebra how *subspaces*, *cartesian products* (which for finite-dimensional vectorspaces covers both products and coproducts) and *dual spaces* show up early, as well as the theorems giving *dimension* as a complete descriptor of a vectorspace.

We'll go through the same sequence here; with some significant small variations.

A category is a *subcategory* of the category if:

- contains for all
- sources and targets of all the arrows in are all in
- the composition in is the restriction of the composition in .

Written this way, it does look somewhat obnoxious. It does become easier though, with the realization - studied closer in homework exercise 2 - that the really important part of a category is the collection of arrows. Thus, a subcategory is a subcollection of the collection of arrows - with identities for all objects present, and with at least all objects that the existing arrows imply.

A subcategory is *full* if for all objects of . In other words, a full subcategory is completely determined by the selection of objects in the subcategory.

A subcategory is *wide* if the collection of objects is the same in both categories. Hence, a wide subcategory picks out a subcollection of the morphisms.

The *dual* of a category is to a large extent inspired by vector space duals. In the dual of a category , we have the same objects, and the morphisms are given by the equality - every morphism from is present, but it goes in the *wrong* direction. Dualizing has a tendency to add the prefix *co-* when it happens, so for instance coproducts are the dual notion to products. We'll return to this construction many times in the course.

Given two categories , we can combine them in several ways:

- We can form the category that has as objects the disjoint union of all the objects of and , and that sets whenever come from different original categories. If come from the same original category, we simply take over the homset from that category. This yields a categorical
*coproduct*, and we denote the result by . Composition is inherited from the original categories. - We can also form the category with objects for every pair of objects . A morphism in is simply a pair . Composition is defined componentwise. This category is the categorical correspondent to the cartesian
*product*, and we denot it by .

In these three constructions - the dual, the product and the coproduct - he arrows in the categories are formal constructions, not functions; even if the original category was given by functions, the result is no longer given by a function.

Given a category and an object of that category, we can form the *slice category* . Objects in the slice category are arrows for some object in , and an arrow is an arrow such that . Composites of arrows are just the composites in the base category.

Notice that the same arrow in the base category represents potentially many different arrows in : it represents one arrow for each choice of source and target compatible with it.

There is a dual notion: the *coslice category* , where the objects are paired with maps .

Slice categories can be used, among other things, to specify the idea of parametrization. The slice category gives a sense to the idea of *objects from labeled by elements of *.

We get this characterization by interpreting the arrow representing an object as representing its source and a *type function*. Hence, in a way, the `Typeable`

type class in Haskell builds a slice category on an appropriate subcategory of the category of datatypes.

Alternatively, we can phrase the importance of the arrow in a slice categories of, say, Set, by looking at preimages of the slice functions. That way, an object gives us a family of (disjoint) subsets of *indexed* by the elements of .

Finally, any graph yields a category by just filling in the arrows that are missing. The result is called the *free category generated by the graph*, and is a concept we will return to in some depth. Free objects have a strict categorical definition, and they serve to give a model of thought for the things they are free objects for. Thus, categories are essentially graphs, possibly with restrictions or relations imposed; and monoids are essentially strings in some alphabet, with restrictions or relatinos.

### Examples

- The empty category.
- No objects, no morphisms.

- The one object/one arrow category .
- A single object and its identity arrow.

- The categories and .
- Two objects, with identity arrows and a unique arrow .

- The category Set of sets.
- Sets for objects, functions for arrows.

- The catgeory FSet of finite sets.
- Finite sets for objects, functions for arrows.

- The category PFn of sets and partial functions.
- Sets for objects. Arrows are pairs .
- is a partially ordered set. precisely if and .

- There is an alternative way to define a category of partial functions: For objects, we take sets, and for morphisms , we take subsets such that each element in occurs in at most one pair in the subset. Composition is by an interpretation of these subsets corresponding to the previous description. We'll call this category .
- Every partial order is a category. Each hom-set has at most one element.
- Objects are the elements of the poset. Arrows are unique, with precisely if .

- Every monoid is a category. Only one object.
- Kleene closure. Free monoids.

- The category of Sets and injective functions.
- The category of Sets and surjective functions.
- The category of -vector spaces and linear maps.
- The category with objects the natural numbers and the set of -matrices.
- The category of Data Types with Computable Functions.
- Our ideal programming language has:
- Primitive data types.
- Constants of each primitive type.
- Operations, given as functions between types.
- Constructors, producing elements from data types, and producing derived data types and operations.

- We will assume that the language is equipped with
- A do-nothing operation for each data type. Haskell has
`id`

. - An empty type , with the property that each type has exactly one function to this type. Haskell has
`()`

. We will use this to define the constants of type as functions . Thus, constants end up being 0-ary functions. - A composition constructor, taking an operator and another operator and producing an operator . Haskell has
`(.)`

.

- A do-nothing operation for each data type. Haskell has
- This allows us to model a functional programming language with a category.

- Our ideal programming language has:
- The category with objects logical propositions and arrows proofs.
- The category Rel has objects finite sets and morphisms being subsets of . Composition is by if there is some such that . Identity morphism is the diagonal .

### Homework

For a passing mark, a written, acceptable solution to at least 3 of the 6 questions should be given no later than midnight before the next lecture.

For each lecture, there will be a few exercises marked with the symbol *. These will be more difficult than the other exercises given, will require significant time and independent study, and will aim to complement the course with material not covered in lectures, but nevertheless interesting for the general philosophy of the lecture course.

- Prove the general associative law: that for any path, and any bracketing of that path, the same composition may be found.
- Which of the following form categories? Proof and disproof for each:
- Objects are finite sets, morphisms are functions such that for all morphisms f, objects B and elements b.
- Objects are finite sets, morphisms are functions such that for all morphisms f, objects B and elements b.
- Objects are finite sets, morphisms are functions such that for all morphisms f, objects B and elements b.

- Suppose in some category .
- If for all in the category, then .
- If for all in the category, then .
- These two results characterize the objects in a category by the properties of their corresponding identity arrows completely.

- For as many of the examples given as you can, prove that they really do form a category. Passing mark is at least 60% of the given examples.
- Which of the categories are subcategories of which other categories? Which of these are wide? Which are full?

- For this question, all parts are required:
- For which sets is the free monoid on that set commutative.
- Prove that for any category , the set is a monoid under composition for every object .

- * Read up on -complete partial orders. Suppose is some set and is the set of partial functions - in other words, an element of is some pair with . We give this set a poset structure by precisely if and .
- Show that is a strict -CPO.
- An element of is a
*fixpoint*of if . Let be the -CPO of partially defined functions on the natural numbers. We define a function by sending some to a function defined by- is defined only if is defined, and then by .

- Describe and . Show that is
*continuous*. Find a fixpoint of such that any other fixpoint of the same function is less than this one. - Find a continuous endofunction on some -CPO that has the fibonacci function as the least fixed point.
- Implement a Haskell function that finds fixed points in an -CPO. Implement the two fixed points above as Haskell functions - using the -CPO fixed point approach in the implementation. It may well be worth looking at
`Data.Map`

to provide a Haskell context for a partial function for this part of the task.