Whenever you’re about to send an email to someone to discuss something, or to ask to schedule time on their calendar, stop – send them a Slack message1Or, whatever is the equivalent of Slack in your context. instead. Whether the other person responds immediately or not, this is a great time-saver, as it streamlines the initial conversation, keeping it quick and informal.
Author: Ramnath R Iyer
A Category Primer
Category theory formalizes mathematical structure. The term ‘theory’ is a misnomer, as there isn’t any hypothesis that’s subject to disconfirmation. Rather, you could think of category theory as a formalism or ‘language’ for expressing the abstract qualities of structures and relationships. It introduces a number of terms and definitions, which I like to call the ‘category zoo’ (which I will explore in a future post).
Wikipedia says, “Category theory has practical applications in programming language theory, for example the usage of monads in functional programming.” I find that statement to be a stretch: while one might find it convenient to express ideas in terms of concepts introduced in category theory, I believe these ideas were perfectly well-articulated even without. My goal then, isn’t to evangelize any practical benefit to understanding category theory, simply to explain what it is.
The Basics
A category is a collection of objects and arrows (aka morphisms) that obey certain rules. Multiple collections may include the same objects and arrows; as long as these rules are obeyed within a collection, the collection is said to form a category.
- Every collection has zero or more objects and arrows.
- Every arrow has a source object and a target object.
- Every collection is closed under composition.
- Composition is associative.
- Every object has a unique identity arrow.
An object is a simple beast, serving simply as the start or end of arrows. It has no further structure to it, and cannot be ‘opened up’. Instead, an object can be defined only in terms of its relationship with other objects, represented by arrows. Multiple arrows may exist between any two (even the same) object. Each of these arrows is distinct. Arrows are given different names to distinguish them from each other.
A category is closed under composition, which means that if you have an arrow f from A to B, and an arrow g from B to C, there must exist, within the collection, another arrow g \circ{} f (pronounced g after f) from A to C which is the composition of the two. Note that there could be many arrows from A to C, but only one of them is g \circ{} f.
Composition is associative, which means that if you have an arrow f from A to B, an arrow g from B to C, and an arrow h from C to D, then we have:
h \circ{} (g \circ{} f) = (h \circ{} g) \circ{} f
In the diagram below, when you take a path from A to D, it doesn’t matter if you take the blue path or the red one, as they’re both equivalent.
An identity arrow of an object X is a unique arrow id_X whose source and target are the object itself, with the additional property that for any arrow f from A to B, we have:
id_A \circ{} f = f = f \circ{} id_B
Notice that these conditions must hold true for any arrow f, not just a particular one. In the diagram below, the blue and red paths are equivalent for any arrow f.
An isomorphism is an invertible morphism (arrow). Given arrows f and f' from A to B and B to A respectively, they form an isomorphism if the following statements hold true.
\begin{aligned} f' \circ f &= id_A \\ f \circ f' &= id_B \\ \end{aligned}
f and f' are inverses of each other. The inverse of an arrow, if it exists, is unique. Two objects A and B are isomorphic if there exists an isomorphism between them, noting in passing that there may be more than one such isomorphism.
An initial object has exactly one arrow to every object in the category (including itself), whereas a terminal object has exactly one arrow from every object. If the source and target are the object itself, then the arrow must be the object’s identity arrow. A category may have any number of initial or terminal objects, or it may have none at all. Initial and terminal objects are duals of each other, identical concepts but with the direction of arrows reversed. In the diagram below, A and F are initial objects, whereas C is a terminal object.
The initial and terminal properties are called universal properties, and an object that satisfies either of these properties is called a universal object. If there are multiple initial objects in a category such as A and F above, then these objects must be isomorphic. Similarly, if there are multiple terminal objects in a category, then they must be isomorphic as well. We say that initial and final objects are ‘unique up to isomorphism’ to express this idea that while the objects may not be identical, there is an isomorphism between them.
Interlude: Category Set
The category of sets, denoted by Set, is one whose objects are sets, and morphisms are total functions from source to target. In this category, each set is nothing more than an object serving as the source or target of one or more morphisms; a categorical description abstracts over the elements contained within any set, leaving behind only how sets relate to each other.
In the category of sets, the empty set is an initial object, as there is exactly one unique total function \mathcal{F_{\varnothing \rightarrow S}} from the empty set to every other set \mathcal{S}. The intuition for this is as follows: since the empty set \varnothing has no elements, it is logically true that if an element from the set were to be provided as input, then it could be uniquely mapped to any of the available sets, including itself. Alas, the empty set is incapable of providing any elements! Notice the parallels with propositional logic, that states that the following is true for any B.
\lnot A \rightarrow (A \rightarrow B)
Further, there is exactly one unique total function \mathcal{G_{S \rightarrow U}} from every set \mathcal{S} to every singleton set \mathcal{U} (a set with exactly one element), as there is exactly one way to construct such a set. Every singleton set is therefore a terminal object. A function mapping every set to a given singleton set is what is conventionally called a constant function — no matter what input you offer, you get the same output, as there is no other alternative.
In the category of sets, as is true for any category, both initial and terminal objects are unique up to isomorphism. Notice that there is exactly one empty set (initial object) and infinitely many singleton sets (terminal objects). All singleton sets are isomorphic, but the empty set is special because it is also unique (and therefore trivially isomorphic to itself through id_\varnothing).
In the diagram below showing a part of the category of sets, \varnothing is the empty set, whereas U_1, U_2 and U_3 are singletons.
Universal Construction
Universal construction is a method of leveraging universal properties to construct new objects. We can observe this method in action in the context of defining products and coproducts.
Product
In the context of sets, a product (or more formally, the Cartesian product) of two sets A and B is A \times B, where:
A \times B = \{(a, b) \mid a \in A, b \in B\}
In category theory, we broaden this definition to apply to any category, and define product in terms of universal properties. We start by observing that the essential property of a product \mathcal{P} is that it can be mapped to two independent projections, a left projection \mathcal{L} and a right projection \mathcal{R}. With this, we define a candidate \mathcal{P'} for the product as an object that can yield \mathcal{L} and \mathcal{R}.
But there may be many such candidates — which one do we pick? For instance, the tuple (X, Y) can be mapped to X and Y, but so can (X, Y, Z) — simply by ignoring Z. We can thus think of each of the remaining candidates as containing some degree of additional noise that should be ignored. In other words, (X, Y, Z) can be uniquely mapped to (X, Y). This is true of any such candidate, and we can represent this idea in the following diagram.
l = l' \circ{} m\\ r = r' \circ{} m
There is a catch, however. You could still have many candidates that look like \mathcal{P}. For instance, both (X, Y) and (Y, X) are equivalent in terms of their information content, and there is no reason to consider one to be a better candidate than the other for \mathcal{P} — they are isomorphic. Or expressed more formally, \mathcal{P} is not unique, but “unique up to isomorphism”.
Coproduct
A coproduct is a dual or inverse of a product, which you can construct by inverting all the arrows from the previous example.
In the context of sets, the coproduct \mathcal{C} represents a disjoint union (also known as tagged union) of \mathcal{L} and \mathcal{R}.
p = m \circ{} p' \\ q = m \circ{} q'
More on the “category zoo” — next time. That’s all for now, folks! 🖖
The Command Pattern
Modularity is a desirable property of any reasonably complex software. Modularity allows the programmer to examine, understand and change parts — modules — of the software while temporarily ignoring the rest of it. When the software becomes too large for a single programmer to work on it sequentially, modularity allows a team of individuals to work on it in parallel. Ideally, modularity is recursive — modules should themselves consist of modules, and so on, until each module is small enough for an individual to grasp quickly, even with an arbitrarily large team.
From one perspective, modularity is less about breaking down software into smaller modules, and more about creating small modules that can be easily combined with other modules to create large systems. Combining modules is called ‘composition’, and composability is the holy grail of software design.
Functions are the ultimate tool in the toolbox of composition. In mathematics, a function has inputs and outputs, and its definition represents the mapping of inputs to outputs. In the computational world, these mappings may be viewed as transformations of inputs into outputs. Functions are inherently composable, as under the right conditions, the outputs of one function may be connected to the input of another function (even itself). Unfortunately, functions in mainstream programming languages are impure in the sense that they may do other things, such as write bytes to disk or send data over a network. These so-called ‘effects’ hinder our ability to compose functions using their mathematical representations, unless the effects themselves are modeled as first-class inputs or outputs.
Only a few languages like Haskell support pure functions — functions that are free of effects. In Haskell, effects are possible only if they are modeled as first-class inputs or outputs. In these cases, effects are encoded into the runtime instances of a special type called IO
, and it is the responsibility of language runtime to execute these effects on behalf of the programmer. For example, in the program below, the main
function returns an IO
instance, and the language runtime executes the effects encapsulated by the instance. In fact, without resorting to backdoor (aka unsafe) techniques, it is not possible to specify effects within a function that doesn’t return an IO
instance. With the IO
type, Haskell programs are smart enough to declare which functions are effectful, and these functions can be distinguished from ones that are not.
import System.IO (BufferMode (NoBuffering), hSetBuffering, stdout)
-- Main program.
-- This function returns an IO instance.
main :: IO ()
main = do
hSetBuffering stdout NoBuffering -- :: IO ()
putStr $ "Enter a number x: " -- :: IO ()
x <- getLine -- :: IO String
putStr $ "Enter a number y: " -- :: IO ()
y <- getLine -- :: IO String
putStrLn $ show $ mult (read x) (read y) -- :: IO ()
-- Multiply two numbers.
-- This function cannot write to disk or send data over the network.
mult :: Int -> Int -> Int
mult x y = x * y
Effects represented by IO
instances can themselves be combined, but only sequentially. In the example above, each line within the main
function returns some kind of IO
instance. These IO
instances are strung together to create a single combined expression…which is itself an IO
instance. Furthermore, the computational results of an IO
instance can never be extracted into a pure function: once you enter the real world, you can never come back.
Object Oriented Languages
In object-oriented languages like Java, composability still remains the holy grail of software development, and so lessons from the functional world are applicable. The essence of the ideas described above can be boiled down into a simple rule of thumb —
When you need to perform an action that deals with the external world, like writing to disk or sending data over the network, encapsulate the action within a ‘command’, and separate the decision of performing the action from actually performing the action.
This separation allows you as the programmer to inspect, re-arrange and re-compose your effectful code easily. Given adequately precise shapes for commands, the compiler will even aid you in making these changes safe. The command interface is analogous to the IO
type in Haskell. And just like IO
, you can string together commands to construct more sophisticated composite ones.
Once you are speaking the language of commands, you can perform computations on the commands themselves. For instance, suppose that instead of printing a message to the screen, you create a ‘log statement’ object that is capable of printing a message to the screen, and then invoke it. You can now enrich all log statements with timestamps, apply filtering based on various criteria and perform other actions before or after you print messages. As another example, suppose that instead of calling a remote web service, you create a ‘service invoker’ object that is given all of the information it needs to call the remote web service, and then invoke it. You can now apply throttling and caching mechanisms that control the flow of how these effects are performed.
The real world is messy, uncertain and error-prone. If we can limit the interactions of our systems with the external world to a few points at the edges, our software is that much more robust, and easier to develop, operate and maintain.
That’s all for today, folks! 🖖