Skip to main content

MAP III - Types of Types II

Updated 31 min readMarkdown
Part of seriesAn Architecture
MAP III - Types of Types II

We need to invert the wasteful trend of learning something as timeless as higher maths only as a means to learn an ephemeral or ever-changing programming language or paradigm. Let's aim instead to explain and discuss foundational mathematical structures like types and categories through these programming languages as visual learning aids. This helps us become better developers in any language, including new ones for quantum computing or even natural language-based programming.

Previously on MAP - Types of Types, we looked at the type hierarchy of Scala and worked with a basic 'level 1' definition of types. Now we will level up and refine our previous working definition of types as value spaces with a set of allowed operations. At level 2, we will celebrate Function's tying of the knot with Data and how that adds a new dimension, literally as well, to how we have come to define and understand types. We will need to go back to discussing some basics like the very concept of functions and objects. With this slightly boring and unapologetically pedantic detour, we will demystify some commonly held oversimplifications or misconceptions and proceed towards the more advanced and interesting concepts being on the same page. For instance we will see how functions and objects together create a fast track towards advanced abstract data types and algebraic structures or how classes and objects are simultaneously quite different and so much more than what we have been teaching our kids.


2. Function weds Data: Domain and Co-domain Spaces

Our last definition of types was mainly concerned with types of data. It was therefore sufficient to think of value spaces, basic syntactics and behavior, understood in the sense of a set of operations on elements of that space. In programming, behavior comes from patterns of actions, which itself comes from operational chunks of code, which in turn act only on either data or other codes.

It's no surprise that chunks of programming instructions and of data have lived together on the same memory space ever since von Neumann architecture was first adopted. This intimacy of data and code is lost on many programmers who do not often need to think of the nitty-gritty of the innards of their machines.

Functions and objects are two major constructs in programming where this intimacy-by-design is directly reflected at the level of program codes. Since they have already 'moved in' together, many languages including Scala make this an official relationship, which I have cheekily phrased as 'function weds data'.

2.1 Object and Class

Just like every construct in Scala has a type, every instance of a type is an object. Scala does not have Java-style primitive types, which do not have objects.

Whether or not a language follows object oriented programming, an object in a programming language is a data abstraction representing value(s) in memory. An object has a named identifier and may have properties, methods with read/write access to the object's properties and relationships with other objects. Like functions, objects have mathematical counterparts too.

An algebra puts values together. A list is built from the empty list and from adding one element to a list, and a function on lists is defined by saying what it does in each of those two cases. A coalgebra works from the other end. It has a state that nobody outside can see, and a step that takes the state and an input and returns an output and the next state. Seen from outside, that is all an object is: its fields are the state, each method call is an input, and what the call returns is the output. A state with such a step is a Mealy machine, the machine that models every party in Unified Computations.

// mealy.ts
/** An object seen from outside: a state nobody else sees, and a step that answers each call. */
export interface Mealy<S, I, O> {
  readonly init: S;
  step(state: S, input: I): { readonly state: S; readonly out: O };
}

/** Make the calls in order and collect the answers; the state never leaves the object. */
export const run = <S, I, O>(m: Mealy<S, I, O>, inputs: readonly I[]): readonly O[] =>
  inputs.reduce<{ readonly state: S; readonly outs: readonly O[] }>(
    (acc, input) => {
      const next = m.step(acc.state, input);
      return { state: next.state, outs: [...acc.outs, next.out] };
    },
    { state: m.init, outs: [] },
  ).outs;

type Call = 'add' | 'read';

/** A counter that keeps a number. */
const byNumber: Mealy<number, Call, number> = {
  init: 0,
  step: (n, call) => (call === 'add' ? { state: n + 1, out: n + 1 } : { state: n, out: n }),
};

/** A counter that keeps every call it was given. */
const byHistory: Mealy<readonly Call[], Call, number> = {
  init: [],
  step: (calls, call) => {
    const kept = call === 'add' ? [...calls, call] : calls;
    return { state: kept, out: kept.length };
  },
};

run(byNumber, ['add', 'add', 'read']); // [1, 2, 2]
run(byHistory, ['add', 'add', 'read']); // [1, 2, 2]

The two counters keep different states, a number and a list of calls, and no sequence of calls can tell them apart. Two objects like that are bisimilar, and to anyone who uses them they are the same object. Bisimilarity does for coalgebras what equality of values does for algebras, and the congruence theorem in Unified Computations rests on it: a party can be swapped for a bisimilar one and the collaboration cannot tell.

Templates

A class is famously known as a 'blueprint' or template for instantiating an object. The class defines what properties, methods and relations an object can have and/or from where it inherits them. A class name is also usually the name of the user-defined type of the objects made using the class's constructor, which also usually has the same name as the class.

This is only partially true in Scala but wholly correct in Scala's more popular cousin Java. In Scala, it is problematic to hold on to the idea of class as a sole blueprint for objects.

The Scala specs define objects, classes and traits (Java 8+ interface-like abstractions supporting states, mix-in type restrictions, reference to objects of implementing classes) in terms of templates, which are not actually available for programmers.

Templates, not classes, are the actual templates in Scala.

A template definition may be a class template definition or an object template definition or a trait template definition. A class definition or an object definition may be for a regular class of objects or a singleton object or for a case class or a case singleton object. These template definitions are what actually define the type signature of the resulting objects and the constructors or initial values therein define the initial states of those objects.

This conception of class in Scala is, as with functions, closer to a class in mathematics in the sense that a class definition represents a constrained set of instantiable objects while an object definition is just for one object.

Scala also throws away the concept of static classes that do not need instantiation in favor of singleton objects created via the object template definition. These static classes, values and methods are hard to reconcile with the object oriented paradigm. They do not support inheritance and dynamic dispatch due to polymorphism, which itself is possible due to inheritance. Lastly they are also tough to mock and unit test easily.

Meta

A class may also instantiate other classes in some languages or object systems like Python, CLOS, Object Pascal, Smalltalk, Ruby and Objective C. Such a class is called a metaclass. An object may also have a meta level or more above it. Such an object is called a metaobject.

As is usual with meta of anything, the metaclasses and metaobjects are parts of advanced concepts in programming. These are useful in understanding reflection, a programming construct's ability to introspect, augment or change its own behavior. In Scala this is achieved via Java's Reflection API and via natively added capabilities since Scala's 2.10 version. The programmer's track (A1 - A3) and the library developer tracks (L1 - L3) are Martin Odersky's Scala levels, three levels for application programmers and three for library designers.

Bonus: Classless OOP

However a class is not the only mechanism for defining templates for object instantiation.

Here's an excerpt from MDN regarding how JavaScript has OOP, better than most other languages known for their OOP, without classes. The ES6 classes are mostly syntactic sugar over prototypes, to make it easier for those used to class based OOP, with a few additions of their own such as private fields.

A prototype-based language?

JavaScript is often described as a prototype-based language — to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from. An object's prototype object may also have a prototype object, which it inherits methods and properties from, and so on.

This is often referred to as a prototype chain, and explains why different objects have properties and methods defined on other objects available to them.Well, to be exact, the properties and methods are defined on the prototype property on the Objects' constructor functions, not the object instances themselves.

The pitfall OOP is best known for is the shared mutable field: two references to one object, one of them writing and the other surprised. Keep the fields read-only and let change arrive as new values, and what remains of OOP is useful: a named bundle of data with the functions that belong to it.

The running code in this series is TypeScript, whose classes are this prototype chain with a class keyword on top. It has Scala's ideas under other names: unknown for Any, never for Nothing, and tagged unions for sealed classes. A reading as an object:

// reading.ts
export class Reading {
  readonly mgdl: number;
  readonly at: string;

  constructor(mgdl: number, at: string) {
    this.mgdl = mgdl;
    this.at = at;
  }

  /** A method returns a new value; nothing is written in place. */
  corrected(mgdl: number): Reading {
    return new Reading(mgdl, this.at);
  }

  /** Declaring `this` makes a detached call a type error. */
  inBand(this: Reading, below: number): boolean {
    return this.mgdl < below;
  }
}

corrected is how an object changes without a shared mutable field: it makes a new reading and leaves the old one as it was. Over a log, that new value is a new record that supersedes the old one, and both stay readable.

2.2 Functions and Methods

A function is a chunk of code you can call by name. The function, its inputs and output can each be objects. In Scala, they always are.

Inputs:

Functions may take values as inputs, possibly operate on these values or create side-effects based on those values or the context, and likely return something in the end. Pure functions however are more well behaved and closer to the functions from mathematics thanks to determinism, referential transparency, and separation from side effects.

Informally speaking, the space of all possible values that could be accepted as an input is called the domain of a function.

Spaces are just sets with added structures. In our context, spaces may have varying dimensionality and each element has its own previously defined level 1 type.

Outputs:

Every chunk of code in Scala that can be put on a single line returns a value.

These lines, which may be typed as blocks for readability, may be either functions or expressions that compose functions. In either case, an output per expression or per function is guaranteed. An expression or function that only handles side effects still returns the previously mentioned Unit, and one that runs into an exception has the type Nothing, because it never returns at all.

This style of programming with expressions is called expression oriented programming (EOP) and is a part of the functional programming paradigm.

Informally speaking, the space of all possible values that could be produced as an output is called the co-domain of a function.

In Scala a method, defined with def, belongs to an object and is not a value itself. A function is a value, an object with an apply method, and Scala turns a method into a function wherever a function is expected. TypeScript draws the same line with this. A method is a function whose first argument is written before the dot: r.inBand(181) is inBand(r, 181) with r passed as this, and that hidden argument is where the second pitfall of OOP lives. Take the method off its object and the argument is gone:

const r = new Reading(142, '2020-04-13T08:00+05:45');
const detached = r.inBand;
// @ts-expect-error: the 'this' context of type 'void' is not assignable to method's 'this' of type 'Reading'
detached(181); // at run time: Cannot read properties of undefined
const inRange = (below: number) => r.inBand(below); // a function that keeps its object

Declaring this in the method's signature turns the mistake into a type error, and passing a function that closes over its object, as the last line does, avoids it altogether. Functions are values, they compose, and a method is one of them with an argument in a special place.


2.3 Parameter Types and Return Types

Now that we are literally on the same page regarding the lingo and the concepts, let's take these concepts to meet some program codes.

Since every line is either a function or an expression, we can simply take note of what type of thing goes in and what comes out.

What goes in is a function's domain and what comes out its co-domain, and the two vary in opposite directions. A function can stand in for another when it accepts at least as much and returns at most as much: functions are contravariant in their parameter types and covariant in their return types.

interface Row { readonly id: string; readonly kind: string }
interface Glucose extends Row { readonly kind: 'glucose'; readonly mgdl: number }
type Handler<A> = (a: A) => void;

const anyRow: Handler<Row> = (row) => console.log(row.id);
const forGlucose: Handler<Glucose> = anyRow; // a handler of any row can handle a glucose row
const glucoseOnly: Handler<Glucose> = (g) => console.log(g.mgdl);
// @ts-expect-error: a glucose handler cannot stand in where any row may arrive
const forRows: Handler<Row> = glucoseOnly;

const nothing: readonly never[] = [];
const rows: readonly Row[] = nothing; // the empty list of Nothing is a list of anything
const readings: readonly Glucose[] = nothing;

The last three lines are where Nothing from the first post on types earns its place. It is the bottom type, a subtype of every type, so under covariance a list of Nothing is a list of anything, which is why Scala's Nil can start every list. Read-only arrays are covariant, and safely so. TypeScript also treats mutable arrays as covariant, which is unsound, and one more reason this series keeps its arrays read-only.

if/else-if/else (v1)

This is commonly needed and commonly avoidable expression. Let's break it down.

How could we write a (basic) version of the if-then expression? We know that it would

  • take a predicate as the first parameter i.e. either a Boolean or something that returns a Boolean
  • take a function to execute if the above value is true as the second parameter
  • the predicate and the function could use any number of parameters of Any type
// Naive if-then without advanced types

def ifThen(someBool: Boolean)(func: () => Boolean): Any = {
  !someBool || func()
}

def unitaryFunc() = {
  false
}

ifThen(true) (unitaryFunc)
// res0: Any = false
// same as the invocation below

ifThen(1 == 2) {unitaryFunc}
// res1: Any = true

ifThen(42 == 42) {unitaryFunc}
// res2: Any = false

This is quite a useless if-then in its current form but it gives us a good outline of how if-then works and what we should improve over the course of this series.

  • As explained in 'Curly Braces and Parentheses' in Viva La Scala explainer collection, the curly braces you see in if statements and other control structures are nothing more than just simple parentheses substituted for readability and multi-line blocks.
  • The if-then structure or p -> q is logically equivalent to ¬p ∨ q

In terms of improvements, these would be highly necessary:

  • We will need to support more types of parameters and return values for the function being passed to the if-then function.
  • We will need to find a way to compose if-then to else-if and else constructs.

Both improvements fit in a few lines of TypeScript. A type parameter lets the branches return anything, and else-if is a list of conditions tried in order, with else as the answer when none of them holds. The branches are passed as functions, so only the chosen one runs, which is what || did for v1.

// cond.ts
/** if-then-else for any result type; only the chosen branch runs. */
export const ifThenElse = <A>(p: boolean, onTrue: () => A, onFalse: () => A): A => (p ? onTrue() : onFalse());

/** else-if: conditions tried in order, the first that holds wins, and `otherwise` is the else. */
export const cond = <A>(cases: readonly (readonly [() => boolean, () => A])[], otherwise: () => A): A =>
  (cases.find(([p]) => p())?.[1] ?? otherwise)();

const band = (mgdl: number): string =>
  cond(
    [
      [() => mgdl < 70, () => 'low'],
      [() => mgdl > 180, () => 'high'],
    ],
    () => 'in range',
  );

band(54); // 'low'
band(240); // 'high'
band(110); // 'in range'

The v1 above also returns true whenever its condition is false, so what it computes is the ¬p ∨ q of the bullet above, the material conditional. An if-then-else has to pick a branch and return what that branch returns, as ifThenElse does. cond is the name Lisp gave the else-if chain, and match with guards behaves the same way, as the next part shows: the cases are tried in order and the first that applies wins.

Function composition, applying one function to the result of another, requires that the return type of the first is the same as the parameter type of the second. How then do you compose functions that need to support incompatible return and parameter types? Section 4 has one solution, the monadic one.

Here's an example of how Java's Optional is converted to the monadic version in Scala:

def toScala[A](o: Optional[A]): Option[A] = if (o.isPresent) Some(o.get) else None

match-case

The above example is a fairly simple use case for if-else because the Optional container has a nice and simple isPresent method that makes it easier to test against a method with Boolean return type. However here's how the reverse condition is achieved by Scala:

import java.util.{Optional, OptionalDouble, OptionalInt, OptionalLong}
import java.{lang => jl}

object OptionConverters {

  def toJavaOptionalInt(o: Option[jl.Integer]): OptionalInt = o match {
    case Some(a) => OptionalInt.of(a)
    case _ => OptionalInt.empty
  }
}

This time we are checking against the possible types. match-case is a better fit for checking against types, which in this case are either Some or anything else.

Note that the match construct is also an expression and the curly braces are once again super-powered parentheses which can take multiline values or functions or expressions as arguments.

The input to the match expression is o provided as the first operand in infix style and the case expressions provided together as the later parameter in the curly braces. The return type is determined by the return type of the expression on the right side of the matched case.

The match-case expression is also capable of checking against values and is especially better suited for cases with too many cases.

def getEnglishNames(x: Int): String = x match {
  case 0 => "Zero"
  case 1 => "One"
  case 2 => "Two"
  case 3 => "Three"
  case 4 => "Four"
  case 5 => "Five"
  case 6 => "Six"
  case 7 => "Seven"
  case 8 => "Eight"
  case 9 => "Nine"
  case _ => "Not enough fingers!!"
}

getEnglishNames(6)
// res0: String = Six

getEnglishNames(10)
// res1: String = Not enough fingers!!

How about mixing these two expressions? If you have a use case where you have to check for values while also checking for types, it's best to use both. Here's how Scala converts FiniteDuration to a Java duration:

  def toJava(duration: FiniteDuration): JDuration = {
    if (duration.length == 0) JDuration.ZERO
    else duration.unit match {
      case TimeUnit.NANOSECONDS => JDuration.ofNanos(duration.length)
      case TimeUnit.MICROSECONDS => JDuration.of(duration.length, ChronoUnit.MICROS)
      case TimeUnit.MILLISECONDS => JDuration.ofMillis(duration.length)
      case TimeUnit.SECONDS => JDuration.ofSeconds(duration.length)
      case TimeUnit.MINUTES => JDuration.ofMinutes(duration.length)
      case TimeUnit.HOURS => JDuration.ofHours(duration.length)
      case TimeUnit.DAYS => JDuration.ofDays(duration.length)
    }
  }

These are pre-existing types. Can we do this with custom types? As we discussed, custom types could come from custom objects or classes. You might have also noticed earlier that class and object template definitions may also have a case qualifier in front of it.

sealed abstract class Device
case class IPhoneX(uglyNotchSize: Long) extends Device
case class S10(holeCamOffset: Double) extends Device
case class NexS(popUpCam: Boolean) extends Device
case class Pixel(pixels: Int) extends Device {
  def sorry = "Old School"
}

def howBeautiful(device: Device): String = device match {
  case IPhoneX(_) => "Ugly"
  case S10(offset) if offset == 0.5 => "Symmetric but Meh"
  case S10(_) => "Meh"
  case NexS(false) => "Cool"
  case NexS(true) => "Clunky"
  case px: Pixel => px.sorry
}


howBeautiful(IPhoneX(10))
// res0: String = Ugly
howBeautiful(S10(0.5))
// res1: String = Symmetric but Meh
howBeautiful(S10(0.7))
// res2: String = Meh
howBeautiful(NexS(false))
// res3: String = Cool
howBeautiful(NexS(true))
// res4: String = Clunky
howBeautiful(Pixel(4))
// res5: String = Old School

The sealed keyword tells Scala that all possible subtypes or cases are present within the same file and not dispersed elsewhere in the code.

The if statement on the first S10 case is another way you could mix if with match. In this case, it is called a pattern guard.

Notice that the ordering of the cases matters: Scala tries them from the top, and the first one that matches wins. There is no fall through to the next case, as there is in the switch statements of many other languages.

Also note that the first five cases are constructor patterns: each checks the case class first and then the values of its fields. Only the last case is a typed pattern, which checks the user defined type alone.

We now have a good groundwork to look into try-catch and try-success-failure, which come with sum types in section 3.1, and into for and for-yield, which come with monads in section 4. That is also where Scala/Mathematics concepts start to get real fun to play with.

The next levels

Here are the next 'levels' of understanding and defining types, each in a section of its own.

3. Abstract Data Types: Types with Structure and Behavior

Here we will rediscover the good old data structures mostly used in programming through a more formal, functional and scala-ble lens 🧐. Sum and product types will also pave the way for the more involved algebraic data types in the later section.

3.1 Sum and Product Types

  • 3.1.1 Union or Tagged Union
  • 3.1.2 Tuple and Record

A tagged union holds one of several cases, and the tag says which. Option and Try from the first post on types are both tagged unions, and so is every closed list in this series, a codec's three answers or the kinds of claim a record may make:

export type Option<A> = { readonly tag: 'some'; readonly value: A } | { readonly tag: 'none' };
export type Try<A> = { readonly tag: 'success'; readonly value: A } | { readonly tag: 'failure'; readonly error: Error };

/** try-catch, once, at the edge; everything after it matches on the tag. */
export const attempt = <A>(f: () => A): Try<A> => {
  try {
    return { tag: 'success', value: f() };
  } catch (e) {
    return { tag: 'failure', error: e instanceof Error ? e : new Error(String(e)) };
  }
};

export const describe = <A>(t: Try<A>, show: (a: A) => string): string => {
  switch (t.tag) {
    case 'success': return `ok: ${show(t.value)}`;
    case 'failure': return `failed: ${t.error.message}`;
    default: { const never: never = t; return never; } // a new case is a compile error here
  }
};

That is the match on a sealed class from section 2.3, written as a switch on the tag, and the never line makes it exhaustive: add a case to the union and every match that forgot it stops compiling. The try-catch happens once, where the failure enters, and after that a failure is a value like any other.

A tuple is a product of positions and a record is a product of names. A row's header in this series is a tuple, [id, kind, deviceId, occurredAt, ...parts], because its signature needs a fixed order, and its body is a record, because two writers must agree on it whatever order they write the keys in. Unit is the product of no types, the 0-tuple, with exactly one value:

type Unit = readonly [];
const unit: Unit = [];

Count the values and the names make sense. A product of types with a and b values has a × b of them, a sum has a + b, Unit has one and Nothing has none. That arithmetic is why these are called algebraic data types.

3.2 Set and List

  • 3.2.1 Unordered and Non-duplicated
  • 3.2.2 Ordered and Random Accessible

A set is unordered and holds each element once. A set that only grows, merged with another by union, is a join-semilattice: union is commutative, associative and idempotent, so two copies merged in any order and any number of times agree. That is the whole of sync between parties in this series, a log being a set of rows keyed by id.

A list is ordered and can be read at any position. The log's order is computed from what each row carries, its time, then its device, then its id, so the list is a view of the set: every party that holds the same rows sorts them into the same list, and nobody has to agree on an order by talking.

3.3 Maps

A map is a finite function from keys to values, and a flat dictionary is a map whose values are never maps themselves. Settings a person edits on two phones are a map from names to stamped values, and two such maps merge key by key with the join on stamps. A pointwise join is a join again, so the merged settings agree in any order:

/** Two maps of settings merge key by key, and a pointwise join is a join. */
export const mergeSettings = <T extends { readonly stamp: string }>(a: ReadonlyMap<string, T>, b: ReadonlyMap<string, T>): Map<string, T> =>
  new Map(
    [...new Set([...a.keys(), ...b.keys()])].map((key) => {
      const [x, y] = [a.get(key), b.get(key)];
      return [key, x === undefined ? y! : y === undefined ? x : join(x, y)] as const;
    }),
  );

join is the stamp merge from Mathematics' Architecture & Processes: the later stamp wins, and equal stamps fall back to the copy's bytes.

3.4 Stack and Queue

A stack takes from the end it last added to and a queue from the end it first added to. An append-only log is a queue that is never taken from. Each reader keeps a cursor, the greatest id it has read from each device, and reads forward from there, so many readers share one queue without any of them removing anything. Undo, the classic use of a stack, becomes a new record that supersedes the one it undoes, and the history stays whole.

3.5 Graph and Tree

The records of a collaboration form a hypergraph: each record joins the parties, files and other records it names, and a record can join more than two. A tree is a view of it, a thread of replies drawn from the record they answer. Because a record names others by their ids and hashes, and a hash can only name something that already exists, the graph of references is acyclic by construction, a Merkle DAG in which nothing can be changed without changing the names of everything that refers to it.


4. Algebraic Data Types and HKTs

Here we will (re-)discover universal algebra, ring-like, group-like, lattice-like, module-like, and algebra-like algebraic structures relevant to advanced functional and reactive programming. We will also demystify higher kinded types and similarly exotic higher order concepts.

Structures by their laws

Universal algebra sorts structures by the laws their operations keep, and each family has a job in collaborative software.

  • Group-like. A monoid is an associative operation with an identity, and logs under concatenation are one, with the empty log as identity. A group adds inverses, and an append-only log has none: undo is a new record that supersedes the one it undoes.
  • Ring-like. A semiring has two operations, addition and multiplication, and provenance is one: alternatives add and records used together multiply. Hamilton's quaternions are a ring whose multiplication does not commute.
  • Lattice-like. A join-semilattice is an operation that is commutative, associative and idempotent, and every merge in this series is one. Monotone programs over a semilattice need no coordination, which is the CALM theorem.
  • Module-like. Vectors that can be added and scaled, the representations a model learns over the records a party holds.
  • Algebra-like. A module with a multiplication of its own, such as the polynomials that provenance builds over records.

Lean checks the monoid laws for logs in three lines:

example (xs : List Nat) : [] ++ xs = xs := rfl
example (xs : List Nat) : xs ++ [] = xs := by simp
example (xs ys zs : List Nat) : (xs ++ ys) ++ zs = xs ++ (ys ++ zs) := by simp

Higher kinded types

List and Option are not types; they take a type and return one. A higher kinded type is a parameter that ranges over such type constructors, and it is what lets one interface say "anything you can map over". Scala and Lean have them, and Lean states the functor laws for Option directly:

/-- Option is a functor: mapping keeps identities and composition. -/
example (o : Option Nat) : o.map id = o := by cases o <;> rfl
example (f : Nat → Nat) (g : Nat → Nat) (o : Option Nat) : o.map (g ∘ f) = (o.map f).map g := by
  cases o <;> rfl

TypeScript has no higher kinded types, so each functor there is written out by hand, map for arrays, map for options, with no single interface over them.

Option as a monad

A monad lets steps that may fail, or branch, or wait, be written one after another. Option is the simplest: each step runs only if the one before it produced a value. Scala writes the sequence with for and yield; Lean writes it with do:

/-- Division that can fail, as an Option. -/
def safeDiv (a b : Nat) : Option Nat := if b = 0 then none else some (a / b)

/-- Two divisions in sequence: the second runs only if the first succeeded. -/
def ratio (a b c : Nat) : Option Nat := do
  let x ← safeDiv a b
  let y ← safeDiv x c
  pure (x + y)

example : ratio 12 3 2 = some 6 := rfl
example : ratio 1 0 2 = none := rfl

/-- A monad law, for Option: binding a pure value is applying the function. -/
example (a : Nat) (f : Nat → Option Nat) : (pure a >>= f) = f a := rfl

safeDiv returns an Option Nat, and the next safeDiv wants a plain Nat, so the two do not compose as functions. The ← composes them anyway, and that is the monadic answer to the question in section 2.3 of how to compose functions whose return and parameter types do not match.

The pattern matching of section 2.3 and the try-catch of section 3.1 meet here: match takes a value apart once, and the monad strings many such steps together without writing the match each time.


5. A Gentle Introduction to Category Theory

Here we will use the Scala concepts and Type Theory topics thus far to go for a deep dive into Bartosz Milewski's excellent course on Category Theory .

Categories, functors and natural transformations

A category is objects, arrows between them, a way to compose arrows, and an identity arrow on each object, with composition associative and the identities doing nothing. Types and functions are one. Logs and appends are another: a log is an object, and an arrow from one log to another says the second extends the first. Polynomials and their maps, the category my paper on collaboration is written in, are a third.

A functor maps one category into another and keeps composition and identities. List.map is one, and so is a view of a log, which sends a longer log to a longer view. A natural transformation moves between two functors the same way at every object. Turning an Option into a list is one, and naturality says it does not matter whether you map before or after:

/-- toList is a natural transformation from Option to List: map, then convert, or convert, then map. -/
theorem toList_natural {α β : Type} (f : α → β) (o : Option α) :
    (o.map f).toList = o.toList.map f := by
  cases o <;> rfl

The meme, explained

Types of Types quotes a meme from James Iry: "A monad is just a monoid in the category of endofunctors, what's the problem?" With the arrows above in place, it can be read word by word. A monad on a category is a functor from the category to itself, an endofunctor, with two natural transformations: a unit that wraps a value, and a multiplication that flattens two layers into one. For List the unit makes a one-element list and the multiplication is flatten. The monoid laws are then the monad laws: flattening is associative, and wrapping is an identity on both sides.

/-- List is a monad, and its multiplication, flatten, is associative: the monoid in the meme. -/
theorem flatten_assoc {α : Type} (xsss : List (List (List α))) :
    (xsss.map List.flatten).flatten = xsss.flatten.flatten :=
  List.flatten_flatten.symm

/-- And it has a unit on both sides. -/
theorem flatten_unit {α : Type} (xs : List α) :
    (xs.map (fun x => [x])).flatten = xs ∧ [xs].flatten = xs :=
  ⟨by induction xs <;> simp_all, by simp⟩

So a monad is a monoid whose elements are endofunctors and whose multiplication is composition followed by flattening. That is what the meme says, and with the arrows written out there is no problem.


Further resources:


  • 1.1 D. L. Parnas, John E. Shore, David Weiss: Abstract types defined as classes of variables, https://dl.acm.org/doi/10.1145/942574.807133

  • 1.2 Tony Hoare on his infamous billion dollar mistake: https://www.youtube.com/watch?v=kz7DfbOuvOM

  • 1.3 Official Scala API Docs and resources: https://www.scala-lang.org/

  • 1.4 L.G. Meredith, Pro Scala: Monadic Design Patterns for the Web: http://patryshev.com/books/GregoryMeredith.pdf

  • 2.3 Bart Jacobs, Introduction to Coalgebra: Towards Mathematics of States and Observation (2016)

  • 3.1 Benjamin Pierce, Types and Programming Languages (2002)

  • 4.1 Eugenio Moggi, "Notions of Computation and Monads", Information and Computation 93 (1991)

  • 4.2 Philip Wadler, "Monads for Functional Programming" (1995)

  • 5.1 Bartosz Milewski, Category Theory for Programmers (2019)

  • 5.2 Saunders Mac Lane, Categories for the Working Mathematician (1971)

About the author

No comments yet. Be the first to comment.

An Architecture

Part 12 of 16

In this series, we explore ways to think about the architecture of common libraries & UIs. We will use JS, Bun, TS, Svelte 5+, Nx, RxJS, ScalaJS, ReasonML, Idris 2+, and Lean 4+.

Up nextMAP - III : Types of TypesMetaTypes and ArcheTypes