Translated from the Chinese author’s manuscript edition, based on the 1102 submission and the author’s separately submitted foreword and final chapter.
Scope
Eight chapters and the references follow the Chinese print edition. The contents, cross-references, and subject index refer to this English edition.
The recent popularity of OpenClaw and its lobster mascot brought a change into focus for me. An agent can now act across models, tools, files, browsers, messaging channels, and the local operating system. It can generate language, invoke tools and skills, and work with both people and programmatic interfaces. Building agents therefore calls for a multilingual view of programming. Python, TypeScript, C#, Swift, Rust, F#, Kotlin, and Scala each bring their own ecosystems and strengths.
A program needs more than a prompt to connect it to an LLM API. Prompts express intent well, but a system contract must also be maintainable over time. We need intermediate representations that give goals, actions, evidence, state, errors, tool calls, and reasoning traces a structure we can parse, verify, and replay. This is how a model’s command of natural language becomes a reusable software component, with a life beyond a single text response.
I use the term “algebraic code” for this way of seeing structure. Algebraic data types (ADTs) organize the possibilities into explicit sums and products. Algebraic pattern matching (APM) expresses rules as branches that can be checked for exhaustiveness. Functor, Applicative, Monad, and Kleisli composition distinguish transforming a value, aggregating independent tasks, and sequencing dependent computations. Together they support precise, auditable reasoning. Data has a shape, rules have a scope, composition obeys laws, and execution leaves a trace.
I therefore approach programming languages along two axes. Object-oriented programming is well suited to entities, encapsulation, lifecycles, interface boundaries, and open extension. Algebraic code handles closed sets of possibilities, structured data, exhaustive dispatch, laws of composition, and verifiable reasoning. The two complement each other in a modern software system. An understanding of OOP helps us reason about objects, state, and collaboration. An understanding of algebraic code helps us reason about types, variants, patterns, and composition. For developers working across languages in the age of agents, both deserve equal standing as foundations for understanding languages and software systems.
That is the starting point for this book. We use algebraic code to understand programming languages, the token paradigm to connect programs to large language models, and verifiable intermediate representations to build agents.
Category Theory Meets Programming: A Roundtable
Imagine a game in which leading ideas from category theory and programming take seats at a round table. Their names and personalities are teaching devices. The chapters that follow give precise definitions, laws, and engineering interpretations.1
Eilenberg and Mac Lane, the founders of category theory, chair the roundtable. Ten guests take their seats. Each brings a motto, a few people or papers to read, an incarnation in code, and some familiar allies.
1. Functor: “Give me a function. I’ll preserve the structure.”
In code: map : (A->B) -> F<A> -> F<B>, as in Option, List, Result, or Task.
At the table: Map, then box; or box, then map. The result agrees.
Allies: Functor lays the groundwork for the rest of the table. Together with Natural Transformation, it lets values move coherently between containers.
2. Applicative: “Combine independent work. Call Monad when one step needs another.”
Nickname: the strategist for parallel work and aggregation.
Key figures: Conor McBride and Ross Paterson (McBride & Paterson, 2008), authors of “Applicative Programming with Effects.”
In code: pure, <*>, and a family of combinators for parallel or independent steps.
At the table: Gather independent steps in one go. Think of validations, forms, and parallel requests.
Allies: Monoidal (guest 7) gives another account of the same structure: Applicative ≈ lax monoidal functor.
3. Monad: “I’ll take care of sequencing and keep the effects inside.”
Nickname: the master of sequencing and handler of effects.
Key figures: Eugenio Moggi established the semantic foundations (Moggi, 1991), and Philip Wadler helped popularize monads and do notation in Haskell (Wadler, 1992a, 1995).
In code: bind/>>=, return, and Kleisli composition (guest 8).
At the table: Join A->M<B> to B->M<C> and get A->M<C>.
Allies: Monad and Kleisli wield a matched pair of blades. Monad shares the work with Applicative: independent work goes to guest 2; dependent work to guest 3.
4. Natural Transformation: “Even a change of containers has rules.”
Nickname: the tai chi master of container changes.
In code: forall A. F<A> -> G<A>, compatible with map:
nt (F.map f) = G.map f ∘ nt.
At the table: I can move the structure without peeking inside the box.
Allies: with Functor it enforces naturality, clearing the way for Traversable (guest 5) to traverse a structure and collect its effects.
5. Traversable: “Turn a structure of effects into an effect containing a structure.”
Nickname: the formation leader.
Key figures: Jeremy Gibbons (Gibbons & Oliveira, 2009) on iteration and traversal, and McBride and Paterson (McBride & Paterson, 2008) on the connection to Applicative. The Haskell community put these ideas to work in Data.Traversable.
In code: sequence : t<F<A>> -> F<t<A>> and traverse : (A->F<B>) -> t<A> -> F<t<B>>.
At the table: Give me a list<Option<A>> and I’ll return an Option<list<A>>.
Allies: Functor and Applicative supply the operations. Naturality ensures that mapping and then traversing agrees with traversing and then mapping appropriately.
6. Alternative / Choice: “If the left branch fails, try the right.”
Nickname: the master of fallback.
Key figures: Ross Paterson (Paterson, 2007) on the design of Haskell’s Control.Applicative, and Daan Leijen and Doaitse Swierstra (Leijen & Meijer, 2001) on applications to parsing.
In code: empty and <|> (or orElse).
At the table: Try A first. If it fails, try B. Useful in parsing, recovery, and search.
Allies: adds monoid-like choice to Applicative, combining candidates according to laws.
7. Monoidal: “Abstract algebra in one hand, Applicative in the other.”
Nickname: the judge.
Key figures in category theory: Saunders Mac Lane (Mac Lane, 1963) and G. M. Kelly (Kelly, 1982) developed the monoidal framework. Programming connection: Conor McBride and Ross Paterson (McBride & Paterson, 2008) explained the equivalence Applicative ≃ lax monoidal functor and its significance in code.
In code: the unit object I, tensor ⊗, and coherence laws for associativity and unit, with natural isomorphisms α, λ, and ρ. These supply the underlying structure of Applicative, including the unit law for pure and associativity and distribution properties involving <*>.
At the table: Give composition a unit and associativity, and it will stand the test of time.
Allies: underwrites the composition laws of Applicative/Alternative and works alongside Natural Transformationand Traversable.
8. Kleisli: “I compose effectful arrows as readily as functions.”
Nickname: the monadic swordsman.
Key figures: Heinrich Kleisli introduced the Kleisli category (Kleisli, 1965). Eugenio Moggi (Moggi, 1991) brought monads and Kleisli arrows into programming semantics, and Philip Wadler (Wadler, 1992b) helped popularize their use and notation.
In code: (>=>) :: (A -> M B) -> (B -> M C) -> (A -> M C), the type of Kleisli composition.
At the table: Compose functions that return M as first-class arrows.
Allies: Monad supplies >>= in arrow form. With Alternative, a long-chain function can fall back at any step. Applicative combines independent work; Kleisli handles dependencies.
9. Long-Chain Functions: Composition and Trailing Closures. “Write the control flow into the types.”
Nickname: the pipeline conductor.
Key figures: Eugenio Moggi (Moggi, 1991) for Kleisli semantics, Philip Wadler (Wadler, 1992b) for pipelines and do notation, the F# community for |> and >>, and the Swift community for trailing closures and chainable APIs.
In code
A curried chain(the specific sense of “long-chain function” in this book):
associates to the right: .
Composition: let h = f >> g >> k in F#, or x |> f |> g to pipe a value.
A Kleisli pipeline for effectful sequencing: f >=> g >=> h : A -> M<C>, with effects such as errors, asynchrony, or state.
Trailing closures in Swift make chained higher-order calls easier to read:
At the table: Prepare → transform → validate → render. Each stage is a first-class value. Give independent steps to Applicative and dependent ones to Monad/Kleisli. Use trailing closures to express local intent at the call site.
Allies
With Applicative: aggregate independent steps that may run in parallel.
With Monad/Kleisli: sequence dependent or effectful steps into a chain.
With Alternative: supply a fallback or another choice at a node (orElse/<|>).
With APM: use pattern matching to express dispatch rules inside the chain as a table.
With Token/KIF: each step produces a Token. Together these form an auditable Trace.
10. ADT–APM: Algebraic Data Types and Algebraic Pattern Matching. “Give data a shape and rules a table.”
Nickname: the dispatch table and its rulebook.
Key figures: Peyton Jones (Peyton Jones, 1987) on functional language implementation and pattern matching, Luc Maranget (Maranget, 2007) on exhaustiveness and overlap warnings, Don Syme (Syme et al., 2007) on F# active patterns, and the OCaml, Haskell, and Scala communities.
In code:
Exhaustive dispatch: match expr with | Case1 x -> ... | Case2 (a,b) -> ... . The compiler checks for missing and overlapping cases.
Active and view patterns: present other data in a matchable view so the rules can follow its shape.
At the table: Structure supplies the grammar; branches state the rules. Write down the table and let the compiler watch its boundaries.
Allies:
A natural pair: the sum-of-products structure of an ADT supplies the shapes, and APM dispatches on them.
With Traversable: when matching or rewriting a batch, turn a structure of effects into an effect containing a structure.
With a UR-Agent: turn rewrite rules and constraints into Horn clauses for SLD resolution and produce machine-checkable proofs.
The Whole Table: A Programmer’s Mnemonic
Functor changes values while holding the structure together; Natural Transformation changes the container consistently.
Applicative gathers independent work, and Monoidal supplies its laws.
Monad/Kleisli handles chains of dependencies.
Alternative provides the fallback.
Traversable turns a structure of effects into an effect containing a structure.
Long-chain functions express control flow in the types.
ADT–APM gives data its shape and arranges rules in a table.
Bring the ten guests together. Start with structure-preserving maps and natural transformations between containers. Combine independent work that can run in parallel using composition with a unit and associativity. For dependencies, use an effectful sequence and allow a fallback choice where needed. For batches, turn a structure of effects into an effect containing a structure. Connect the main workflow with a pipeline of curried, pure functions, and dispatch decisions through algebraic pattern matching. Record the outputs as Token / Proof / Citations / Trace so they can be read, computed over, verified, and managed. This is how we write control flow into types, carry semantics in containers, and attach evidence to artifacts.
This playful account is meant to build intuition. For historical detail, formal definitions, and arguments, consult the chapters and references.↩︎
Preface
This book begins with the token and follows four lines of work that are often treated separately: algebraic code, structured representation through algebraic data types (ADTs) and their variants, LLM reasoning and agent collaboration, and neural network inference and automatic differentiation. Large models gave us language as an interface. Since the introduction of the Transformer, attention-based networks have become a general computational architecture, and training them at scale has brought extraordinary expressive power and transfer capabilities. One difficulty persists: a beautifully worded answer can be hard to verify. Where did it come from? Does the reasoning hold? Can we reproduce and audit it? The difficulty lies in the gap between the form of the answer and what engineering requires. Natural language serves human communication well; our systems need objects they can compose, trace, and execute. Meanwhile, neural networks themselves are acquiring a more programmatic representation. ONNX (ONNX Project, 2025) uses graphs and operators as an intermediate representation (IR), versions operator semantics, and leaves execution to a runtime. On the training side, automatic differentiation expresses learning through the chain rule on a graph. We can organize the forward and backward passes as composable programs. In this sense, both inference and learning are algebraic. Our task is to give them suitable interfaces and contracts.
Language may be an interface, but software needs structure it can compose, verify, and replay. Algebraic code offers a direct approach. Long-chain (curried) functions and combinators connect computations. Sum types and ADT variants describe the legal shapes of data. Algebraic pattern matching (APM) dispatches on those shapes and checks coverage. These facilities are now common in mainstream languages. Extensible objects and enumerable data shapes have begun to meet, and algebraic code supplies abstractions stable enough to work across both. The same engineering patterns can travel among Swift, F#, Scala, Kotlin, Rust, C#, and other languages. The chapters that follow show how.
1. Our Approach: Algebraic Code and the Token Paradigm
We bring ADT variants and ideas from category theory to LLM and agent engineering. Types and pattern matching organize knowledge, reasoning, tasks, and effects so that AI code, like a design pattern, can be reused, verified, and evolved. By the token paradigm we mean the following process. An LLM first produces structured tokens through a constrained schema or function call. We represent those tokens with a strictly typed ADT and pass them to an execution or inference engine whose behavior can be checked. Structured output and function or tool calling can bind generation directly to JSON Schema and program interfaces, reducing cleanup and making replay easier.
Our subject extends beyond functional programming. Programmers can work with functions, methods, and function pointers without appealing to the lambda calculus, although the lambda calculusremains a minimal model for functional semantics. Category theory gives us an abstract mathematical language for structures and their composition that travels well between domains. It distinguishes and names different structures for combining functions, including functors, natural transformations, and monads. Our concern is the ability to model algebraically with ADTs, pattern matching, immutable data, combinators, and effect abstractions. These facilities do not depend on the purity of a lambda calculus. They let us organize code so that we can compose it and prove properties about it. The ubiquitous long-chain function is a programming counterpart of a categorical idea. In ADT programming we analyze how meanings compose, then organize and name what a token sequence carries as abstract syntax (an AST) and algebraic sums and products. These are central to the token paradigm.
2. Algebraic Code Across Languages: Composition Alongside OOP
The minimal grammar of algebraic code is ADTs (sums and products) plus pattern matching. This combination is now common infrastructure in mainstream languages:
In Swift, an enum case can carry associated values, and patterns decompose the alternatives exhaustively (Apple Inc., 2024a).
In Kotlin, sealed hierarchies and when expressions provide a closed set of cases and an exhaustiveness check (JetBrains Kotlin Team, 2025).
TypeScript directly supports discriminated unions and control-flow narrowing, modeling ADTs and safe case analysis at the type level (TypeScript Team, 2025a, 2025b).
Java introduced sealed classes (JEP 409) in JDK 17 and pattern matching for switch (JEP 441) in JDK 21. These bring data-oriented modeling and exhaustiveness checks to a traditionally object-oriented language (OpenJDK, 2021, 2023).
In C#, pattern matching in is and switch supports dispatch on structure (Microsoft, 2025).
F# combines discriminated unions and records with exhaustiveness checking in match. Result<'T,'E> is a struct discriminated union with a module of combinators including Result.map, Result.bind, and Result.mapError (Microsoft Learn, 2021a, 2021b).
Haskell combines data and newtype declarations with pattern matching. See the official Haskell 98 and Haskell 2010 reports (Marlow, 2010a).
The common idea: a closed hierarchy with pattern matching enumerates the legal states, lets a compiler check for missing cases, and expresses domain invariants up front. Algebraic code gives object-oriented programs a powerful data-oriented technique for composition.
3. Category Theory in Mainstream Languages
Categorical abstractions are another important part of algebraic code: category theory views algebra from a particularly high level of abstraction. In modern languages, long-chain functions (currying) turn a multiargument function
into an equivalent chain that accepts A first and B next:
,
This naturally supports partial application and composition in pipelines. The trailing closures of languages such as Swift, including its support for multiple trailing closures, make it easier to fix one argument and continue building the chain. An API becomes easier to compose and can express more in a few lines. The categorical counterpart is the exponential-object isomorphism, also called the exponential law or currying isomorphism:
,
Giving an arrow out of a product is equivalent to giving an arrow into the function space . Currying and composition express this law at the level of types.
The categorical abstractions Functor, Applicative, and Monad are already present in everyday APIs:
Functor → map: apply a pure transformation inside the same outer structure, as with Optional.map or Sequence.map.
Applicative → zip or parallel alignment: combine several values in parallel when they are independent.
Monad → flatMap/bind: sequence dependent computations. For example, flatMap on Optional, Sequence, AsyncSequence, and Result handles optional synchronous values, collections, asynchronous streams, and error propagation, respectively (Apple Inc., 2025a, 2025b, 2025d, 2025c).
This approach draws on Moggi and Wadler. Categorical semantics describes computations and effects, and a monad organizes effects such as I/O, exceptions, and state under the identity and associativity laws. See Chapter 2.
4. Algebraic Code in Neural Network Inference and Learning
In deep learning, a network is an algebraic composition of operators. ONNX turns this idea into a standard. Its IR represents models with graphs and operators. An operator can be primitive, or a function can be defined by expanding it into a subgraph. The IR and operators are independently versioned, and ONNX Runtime executes compatible operator sets. A computation graph is thus a rewritable, composable algebraic object. On the training side, PyTorch autograd (PyTorch Core Team, 2025) dynamically records a directed acyclic graph during the forward pass. The chain rule connects leaf tensors to the root, and the backward pass follows the graph to compute gradients. Learning becomes algebraic differentiation on a graph. In .NET, TorchSharp (.NET Foundation & Microsoft, 2025a, 2025b) binds directly to LibTorch. Its tensor, module, and gradient APIs follow PyTorch semantics, making the same combination of algebraic graphs and automatic differentiation available in F#. Chapters 4–6 model networks and operator graphs with ADTs and describe learning using ReverseGraph and AD (JVP/VJP). Chapter 5 connects the representation to Transformer nodes and operators. Together these chapters show how algebraic code spans inference (the forward pass) and learning (the backward pass).
5. Connecting Agents to Large Language Models
We treat an agent as a collection of algebraic interfaces governed by contracts. Retrieval turns external material into structured records with provenance, inference checks conclusions against rules, and the LLM translates between natural language and these structures.
Chapter 1 illustrates the distinct responsibilities of retrieval and inference with the AR-Agent and UR-Agent. The later chapters concentrate on the more stable foundations: representation, composition, lowering, automatic differentiation, and executable semantics.
We begin by using algebraic code and the token paradigm to connect language and programs. We introduce the basic vocabulary and contracts: long-chain (curried) functions and combinators; sum types, ADT variants, and APM; structured output and function or tool calls; and the division of responsibilities between the AR-Agent and UR-Agent.
Types and categories give a common account of modern composition: map, zip, and flatMap correspond to Functor, Applicative, and Monad. The exponential-object isomorphism underpins currying and partial application. We generalize the passage from transforming values to transforming values in context into programming laws that support reasoning.
Sums, products, unit, and the empty type give us a syntax and equational laws for constructing ADTs. We show how APM checks exhaustiveness and dispatches on shape, then compare ADTs and OOP and show how to bridge them.
We treat a network as an algebraic composition of operator graphs. ADTs describe tensors, operators, and subgraphs. Relating a cross-framework IR such as ONNX to its runtime makes our working assumption explicit: a graph is a composable program.
GPT-2 and attention make the abstraction concrete. We relate nodes, operators, and parameters to ADT structures, map the operator level to the module level, and show how an algebraic graph supports inference in practice.
We describe learning as differentiation on a graph, using JVPs, VJPs, reverse mode, and ReverseGraph. We show how ADTs organize the training loop from the forward pass through backpropagation to an optimizer update, and what the implementation needs to get right.
From compositional semantics we develop an executable approximation. Syntax, semantics, and constraints become exchangeable ADT fragments and rules. We translate stretches of text into structured tokens and follow the path from language through representation to executable checks.
The model proposes candidates, algebraic structure bounds the legal shapes, programs execute them, and evidence and rules verify the results. Three principles sum up the relationship: representation before generation, composition before scale, and verification before acceptance.
The core edition keeps the durable concepts, methods, and full arguments in the text. Assignments, starter code, and acceptance criteria change more quickly and live together in the open-source repository, where they can be run, tested, and maintained.
7. Readers and Classroom Use
Practicing engineers can connect RAG, inference, type systems, and deep network training in a pipeline ready for deployment.
Graduate students and researchers can relate semantics, types, reasoning, and learning within one set of abstractions.
Instructors can proceed from structure to models, differentiation, and then knowledge and reasoning. The companion repository provides exercises that emphasize running code and verifying results.
Open-source repository for examples and starter code:
This book grew out of technical work and can also serve as a textbook for a course on algebraic code and AI frameworks. Our aim is to give students, researchers, and practitioners a theoretical foundation, a practical guide, and ideas to carry into their own work.
We believe that algebraic code and large language models together will help shape the next wave of technological change. We hope this book encourages readers to think further, develop the field, and put its advances to work for the benefit of others.
10. Funding
Publication was supported in part by a 2023 Sichuan University Higher Education Teaching Reform Project (tenth round, project SCU10337). The book also benefited from teaching reform and seed-funding projects at the university’s College of Computer Science and College of Software Engineering in recent years.
An Overview of Algebraic Code and the Token Paradigm
This book starts from a simple idea: write code algebraically, then connect that composable code to an LLM. Over the past thirty years, ideas from category theory have entered programming through Haskell, giving us three powerful tools for composition: Functor, Applicative, and Monad (FAM). Moggi (Moggi, 1991) used monads to give a unified account of the semantics of computation. Wadler (Wadler, 1992b, 1995) turned that account into a practical way to organize exceptions, state, I/O, and nondeterminism. McBride and Paterson (McBride & Paterson, 2008) subsequently identified Applicative as the abstraction for combining independent steps. This gave us three levels of composition: transform a value (Functor), combine independent computations, possibly in parallel (Applicative), and sequence dependent computations (Monad). We still draw on that tradition when building reliable systems. Meanwhile, mainstream languages have made algebraic data types(ADTs) first-class citizens. Algebraic Code is an everyday tool for modeling and composition.
In the age of LLMs, composability must extend to interactions with models. RAG (Y. Huang et al., 2024; Lewis et al., 2020) allows a generative model to draw on external knowledge on demand, reducing hallucinations and making sources traceable. Approaches such as ReAct (Yao et al., 2023) interleave reasoning and action so that the model can look things up as it reasons and leave a record that can be interpreted and corrected. Algebraic Code gives us a structure we can refactor, the token paradigm gives us a language for communication, and LLMs and protocols connect the two. Beginning with long-chain functions and combinators, we will assemble these capabilities into intelligent systems that can be verified, maintained, and extended.
This chapter maps out the terrain:
1.1 Engineering Motivations and Context explains why algebraic composition belongs alongside LLMs and works backward from verifiability, maintainability, and traceability to the capabilities we need.
1.2 A Map of Algebraic Capabilities uses the three levels of FAM to characterize the semantics of composition and ADTs and combinators to describe composable structures for data and behavior. Applicative supplies the essential middle level for parallel or aggregate operations.
1.3 The Token Paradigm brings structured, token-oriented representations together with the natural-language output of LLMs so that we can move between verifiable structures and intelligible expressions.
1.4 LLMs and Algebraic Agents previews the custom agent framework used throughout the book (AR-Agent and UR-Agent) and shows how protocols and combinators join retrieval, planning, and execution into an observable sequence.
1.5 A Quick Example turns a list of rules into a runnable program in about 30 lines of Algebraic Code, taking the shortest path from structure to computation to binding.
1.6 Reading Paths offers a short route into the material for readers from an object-oriented background or those who mainly write Swift, F#, or Rust.
1.1 Engineering Motivations and Context
Software engineering teams are feeling the strain of object-oriented programming (OOP). Class hierarchies grow ever taller, implicit state spreads, and framework “magic” hides dependencies. For many teams, a small change can ripple through the whole system. Meanwhile, AI is making it faster to write a piece of code that runs. The scarce resources are now verifiable abstractions and composable structures.
We therefore raise the level of abstraction above our existing OOP assets, using algebraic design patterns to assemble systems. Consider two representative tools.
Algebraic data types (ADTs) provide a general representation of domain knowledge at the level of syntax. They can describe discrete domain structures to virtually any degree of precision required in engineering. Sums, products, and recursion capture states, events, and their relationships. Exhaustive matching turns missing cases into compile-time errors. Smart constructors, invariants, and rule checks can then encode semantic constraints in the types and construction paths, representing our understanding of a domain as precisely as the application requires.
A long-chain function (LCF) in this book means a curried function: a function of several arguments rewritten as a right-associative chain of arrows
,
that is, a function that returns a function. An LCF naturally supports partial application and the injection of capabilities or environments, as in
Env Input Result,
which moves side effects and context to the call boundary, reducing implicit state and coupling in the core computation. An LCF is distinct from method chaining or a pipeline of composed functions. Currying stages arguments at the type level, whereas a pipeline joins steps at the value level. By injecting capabilities and moving side effects outward, long-chain functions define effect boundaries and naturally support partial application and composition. Effects such as concurrency, I/O, and errors become visible in the types, where we can reason about and test them.
ADTs and LCFs extend well beyond traditional functional programming. These building blocks work across paradigms and already occur in everyday Swift, Kotlin, Rust, Scala, F#, TypeScript, and C#. We advocate building on OOP by making context explicit, expressing constraints in types, and giving workflows an algebraic structure. Complexity becomes visible, composition becomes the default, and verification moves toward compile time. In an era of AI-assisted development, code that runs can also be reasoned about, evolved, and reused.
Both ADTs and long-chain functions (LCFs, or curried functions) have algebraic roots. The latter arise from the currying isomorphism in category theory, itself an algebraic language and method. This is why we call the approach “Algebraic Code.”
Large language models (LLMs) have also changed how we generate and execute software logic. Given natural language, an LLM can generate structured output, such as code fragments or data in a specified format. We call this “the token paradigm” (Tokenism). It centers on the token, the basic unit of LLM output, as a carrier of structured information. The token paradigm inherits the symbolist use of symbols to express explicit rules while drawing on the powerful language-generation capabilities of connectionism, or deep learning (Xiong et al., 2024). The move from hand-coded rules in symbolic AI to LLM-generated structured results marks a shift from symbolism toward the token paradigm.
Two trends thus shape software development. Engineers are turning to algebraic programming with long-chain functions and ADTs to improve quality and maintainability. They are also using LLMs to produce structured information through a Token KIF interface, reducing repetitive coding. The following sections develop this picture.
1.2 A Map of Algebraic Capabilities and the Role of Category Theory
These developments call for an engineering approach that safely integrates LLM capabilities into conventional software. This is the motivation for Algebraic Code: we draw on formal methods from algebra and category theory to build an algebraic capability stack for intelligent applications that are composable, amenable to reasoning, and easy to audit.
The stack has two foundations. One consists of type-system and program-structure features exemplified by algebraic data types (ADTs), which precisely characterize data and state spaces. The other consists of abstract models grounded in category theory, which describe computational processes, especially computations with side effects, at a higher level.
Category theoryand abstract models of computation. Category theory supplies abstractions that unify different concepts of computation. In software these include general interfaces such as Functor, Applicative, and Monad. They give us structured ways to handle side effects. A functor supports mapping in a context: we apply a function to a value held within that context. An applicative functor lies between Functor and Monad. It allows computations in independent contexts to be sequenced and their effects combined without knowing previous results. A monad lets us chain computations, feeding each result into the next step and connecting effectful operations in the form of pure functions. As Wadler (Wadler, 1995) observed, monads offer a convenient framework for modeling global state, exception handling, output, and nondeterminism in a pure functional language. Functor, Applicative, and Monad let us encapsulate side effects in a structure governed by types and composition laws. Effects that would otherwise spread throughout a program can thus be managed within algebraic structures.
Together these foundations give the algebraic capability stack a repertoire spanning type systems and abstractions for computation. It includes parametric polymorphism (Reynolds, 1983b), introduced by Reynolds so that a function can exhibit uniform behavior at any type, as well as higher-order functions (which take or return functions), immutability, pure functions, lazy evaluation, and function composition. The table below introduces abbreviations for these capabilities. Together they give LLM-driven applications a firm engineering foundation: data have an explicit algebraic structure, and computations obey provable laws of composition, making systems easier to reason about and verify.
What capabilities does algebraic programming depend on, and how well do mainstream languages support them? They span type systems, functional programming, and categorical abstractions. We assign each an abbreviation and compare support across 13 common languages. The following twelve capabilities cover the principal elements of algebraic programming, from polymorphism to function composition.
PP (Parametric Polymorphism / Generics). Type variables allow us to express a function or data structure that works for all types, preserving uniform behavior across instantiations. This is parametricity. Reynolds’s (Reynolds, 1983a) abstraction theorem laid the theoretical foundation for generic type systems: types classify values and logically constrain abstraction and invariance. This idea influenced the type designs of System F, ML, F#, and Haskell and provides Algebraic Code with unified semantics for abstraction and composition. An important point here is that functors on parameterized types often have a counterpart in categorical natural transformations.
LCF/CUR (Long-Chaining / Currying). Support for currying converts a function of several arguments into a succession of single-argument functions.
ADT (Algebraic Data Types / Variants). Support for algebraic data types, including variant types such as enumerations and unions.
AE (Algebraic Effects). Algebraic effects represent side effects as composable operations. They are usually paired with effect handlers, allowing effects to be introduced and managed declaratively instead of repeating handling logic at every use site. Effects can then be passed and combined like data. Languages such as Eff and Multicore OCaml, along with research on effects, explore whether this offers a more flexible way to model side effects than monads.
APM (Algebraic Pattern Matching). Pattern matching decomposes and processes data directly according to their structure. It often goes hand in hand with ADTs: each constructor can have a corresponding branch. The result is concise code, and a compiler can check exhaustiveness to ensure every case is handled. Pattern matching is central to Haskell, F#, Scala, Rust, and Swift.
PF (Pure Function). A pure function has no side effects: its output depends only on its inputs, and it changes no external state. Pure functions are referentially transparent, amenable to caching and reasoning, and well suited to parallel computation and testing. Functional programming builds on this principle by expressing program logic in pure functions and isolating side effects in a small part of the program.
IM (Immutability). This is support for immutable data, including variables and data structures that are immutable by default. Once created, such data cannot be modified. Immutability eliminates problems caused by shared mutable state, makes concurrency safer, and simplifies reasoning. Many languages, including Java and C#, have introduced libraries of immutable data structures. Scala and Kotlin encourage val (an immutable binding) as the default choice. Immutability and pure functions often go together, making program behavior more deterministic.
HOF (Higher-Order Function). A higher-order function accepts a function as an argument or returns one. Treating functions as first-class values allows us to build program logic at a higher level of abstraction, for instance with callbacks, the strategy pattern, or lambda expressions. Almost every modern mainstream language supports higher-order functions; Java’s introduction of lambdas in version 8 is one example of this shift.
LE (Lazy Evaluation). Lazy evaluation defers the evaluation of an expression until its value is needed. It can avoid unnecessary computation and permits infinite data structures. Pairing laziness with pure functions helps prevent unexpected side effects. Haskell is lazy by default. Most eager languages also offer mechanisms for lazy evaluation, such as Java’s Supplier<T> and Python generators.
FAM(Functor → Applicative → Monad). A language or library should support the composition semantics of map for Functor, pure/ap (or zip/mapN) for Applicative, and flatMap/bind for Monad. A monad organizes such effects as I/O, exceptions, state, nondeterminism, and asynchronous execution into composable sequential computations. Moggi laid the foundation in his categorical semantics of computation. Wadler showed how to use monads in practice to handle exceptions, state, output, and nondeterminism cleanly. Applicative describes parallel execution or aggregation of independent steps. It lies between Functor and Monad and is less expressive than Monad, but its computations are easier to parallelize and reorder. This middle abstraction occurs frequently in modern code. City Research Online. Industrial languages commonly offer monads or equivalent patterns. In Scala, Option and Either provide map/flatMap and can be sequenced in a for-comprehension. In JavaScript, Promise.then() returns a new Promise and supports chaining with the semantics of bind. In Java, Optional provides map/flatMap with similar semantics for potentially missing values, although it is not a general-purpose effect monad. In programmers’ shorthand: it is difficult to read Haskell-style composable code fluently without understanding Monad. Choose the level you need: map to change a value, mapN/zip to combine independent steps, and flatMap when steps depend on earlier results or may short-circuit.
FC (Function Composition). This is syntactic or library support for combining functions into pipelines. Connecting the output of one function to the input of another produces a new function, the programming counterpart of mathematical composition. We can assemble complex computations from simpler ones. Many languages supply composition operators or methods, such as F#’s >> operator or the facilities provided by lodash in JavaScript. Together, higher-order functions and composition let us build pipelines for processing data with less code and clearer semantics.
C (Lambda Closures). Anonymous functions are a common form of closure. A closure provides concise syntax and captures free variables in its lexical scope, carrying that state into execution. Closures support functional patterns such as map/reduce and event callbacks. They are widely available in languages ranging from systems languages such as C++ to high-level languages such as Python.
The following table compares these algebraic capabilities across 13 modern programming languages.
Table 1-1. Algebraic capabilities of 13 modern programming languages. A check mark (✓) indicates strong or native support, a tilde (~) indicates support through libraries, conventions, or other non-native means, and a dash (–) indicates an absent or uncommon feature. The JS/TS entry primarily reflects TypeScript. C++ denotes C++11 and later, although ADTs require C++17 std::variant or a library. Java uses Java 8+ as a baseline; later versions improve support for sealed hierarchies and pattern matching.
Language
PP
ADT
AE
PM
PF
IM
Haskell
✓
✓
~
✓
✓
✓
Python
~
~
–
~
~
~
JavaScript /
TypeScript
✓
✓
–
~
~
~
C++11+
✓
~
–
–
~
~
C#
✓
~
–
~
~
~
Scala
✓
✓
~
✓
~
✓
F#
✓
✓
~
✓
~
✓
Go
✓
–
–
–
~
–
Rust
✓
✓
–
✓
~
✓
Kotlin
✓
✓
–
✓
~
✓
Swift
✓
✓
–
✓
~
✓
Java 8+
✓
~
–
~
~
~
Table 1-1 (continued). Algebraic capabilities of modern programming languages
Language
HOF
LE
FAM
FC
C
LCF
Haskell
✓
✓
✓
✓
✓
✓
Python
✓
~
~
~
✓
~
JavaScript /
TypeScript
✓
~
~
~
✓
~
C++11+
✓
~
~
~
✓
~
C#
✓
~
~
~
✓
✓
Scala
✓
~
✓
✓
✓
✓
F#
✓
~
✓
✓
✓
✓
Go
✓
–
~
~
✓
~
Rust
✓
~
~
~
✓
~
Kotlin
✓
~
~
~
✓
~
Swift
✓
~
~
~
✓
✓
Java 8+
✓
~
~
~
✓
~
Functional languages such as Haskell and F# perform well on almost every dimension. Java and Python, by comparison, have notable gaps in areas such as ADTs, immutability, and lazy evaluation. Mainstream multiparadigm languages such as Swift, Rust, Kotlin, and C# increasingly incorporate algebraic features and occupy the middle of the map. Swift supports ADTs and pattern matching with enum and switch. Rust has ADTs (enum) and immutable bindings by default. Both still use imperative, eager execution by default. Overall, modern languages are moving toward algebraic programming. The map makes their respective strengths and limitations visible when choosing an implementation language or migrating code.
These capabilities work together as a toolkit for Algebraic Code. Algebraic data types and pattern matching express complex logic concisely and let the compiler check exhaustiveness. Pure functions with immutable data produce predictable, testable units of logic. Higher-order functions and currying make it possible to write reusable general-purpose combinators. A monad provides an interface governed by laws such as associativity and identity for chaining operations in error handling and asynchronous computation. Later examples show how these capabilities work together in software architectures for the LLM era.
1.3 The Token Paradigm: Structured Representations and LLM Output
Traditional symbolic AI relies on structured representations such as knowledge graphs and logical rules to enable machines to “understand” a problem. A large language model typically emits unstructured text as a sequence of tokens. The token paradigm brings the two together by introducing structure into the generated sequence, retaining the model’s linguistic flexibility and the explicitness of symbolic representations.
The problem. Traditional symbolic AI emphasizes structured representations such as knowledge graphs, logics, type systems, and semantic categories to ensure composability, verifiability, and reuse. LLMs naturally generate unstructured token sequences. They excel at language generation and heuristic reasoning, but their output can be difficult to verify and may contain hallucinations. Aligning the two has become a central research question. Here the token paradigm means embedding structure (schemas, grammars, constraints, or evidence) in the sequence generated by an LLM, then materializing it as computable abstract data types and verifiable semantic objects. The result preserves the model’s generative capabilities while giving its output a precise, auditable symbolic interpretation.
1.3.1 Theoretical Background of Structured Representations
Compositionality and formal semantics. Beginning with Montague (Janssen, 2008), formal semantics has adopted the principle of compositionality: the meaning of a whole is determined by the meanings of its parts and the way they are syntactically combined. Model-theoretic semantics remains a mainstream framework for logical languages and formal semantics, providing a basis for mapping natural language to computable meaning representations.
The semantic parsing tradition. Semantic parsing studies the mapping from language to logic or programs, seeking both structural validity (correct syntax and types) and executable semantics (a result that can run against a knowledge base or in an interpreter). Recent surveys describe multiple routes from sequences to logical forms, SQL, and programs, including hierarchical and sketch-and-refine decoding strategies and weakly supervised learning. They illustrate the need for tightly constrained structured output in complex tasks (P. Jiang & Cai, 2024).
Implication. If an LLM is to serve as a powerful language interface whose products can be used in software, we must return to structure and to composable representations.
1.3.2 Strengths and Limitations of LLM Output
Language-driven decomposition and reasoning. Chain-of-thought (CoT) prompting has shown that explicitly generating intermediate reasoning steps can markedly improve performance on complex reasoning tasks in sufficiently large models. The effect emerges with scale (Wei, Wang, Schuurmans, Bosma, et al., 2022).
Coupling reasoning with action. ReAct alternates the generation of a Thought and an Action so that a model can gather evidence in an external environment as it reasons, iteratively revising its plan (Yao et al., 2023).
Vulnerabilities: hallucinations and unverifiable output. Studies show that LLMs carry systematic risks of hallucination in both factual accuracy and consistency. Mitigation calls for external knowledge, structural constraints, and independent verification (L. Huang et al., 2023).
Implication. High-assurance applications can use the language capabilities of LLMs only when the output is structured and backed by evidence.
1.3.3 Three Paths from Token Output to Structured Tokens
Structured or constrained decoding
Mechanisms such as JSON or schema-constrained output and function calling can constrain the model during generation, placing information in a parseable schema with specified fields, types, and value domains. Mainstream APIs offer integrated support for structured output, JSON mode, and function calling, connecting prompting to constraint enforcement and parsing (Google DeepMind, 2025b, 2025a; Microsoft Azure AI, 2025; OpenAI, 2025b, 2025a).
The theoretical significance is that generation is bound in advance to a decidable domain of formats, types, and syntax. This reduces downstream cleanup and improves reproducibility and composability.
Delegating reasoning to a verifiable executor
In program-aided and program-of-thought approaches, the LLM translates natural language into a program or DSL as an intermediate representation and delegates solving to an interpreter or solver, substantially reducing errors in arithmetic and symbolic reasoning. PAL illustrates the general advantage of generating and interpreting a program over reasoning entirely in natural language (Chen et al., 2022; Gao et al., 2022; Wei, Wang, Schuurmans, & others, 2022).
The theoretical significance is that an unverifiable answer produced in one linguistic step becomes a sequence from language to structure to execution. Responsibility for correctness passes to an execution system with explicit semantics.
Integrating external knowledge in structured form
RAG connects nonparametric memory (a document index) to generation, substantially improving factual accuracy. Both theory and experiment show how retrieval and generation complement each other (Y. Huang et al., 2024; Lewis et al., 2020).
GraphRAG goes further by extracting a knowledge graph from documents. It aligns relations across documents and passages and supports multihop reasoning while accommodating scale and traceable provenance (Janssen, 2008).
Summary. These approaches constrain form through decoding, delegate semantic execution to programs or reasoning engines, and introduce verifiable external knowledge through RAG or knowledge graphs. Together they turn unconstrained tokens into structured tokens.
1.3.4 Relation to Neuro-Symbolic Integration
A recent survey of neuro-symbolic approaches argues that a principled integration of trainable neural networks with interpretable symbolic systems capable of reasoning requires composable interfaces and consistent semantics at the levels of representation, learning, and inference. This agrees with the token paradigm’s use of schemas at generation time and enforcement of semantic alignment at execution time (d’Avila Garcez & Lamb, 2023).
1.3.5 Conclusion
The token paradigm goes beyond reducing LLM errors. Its central idea is to translate generated output into structure, connect structure to semantics, and submit those semantics to verifiable execution. Its three pillars are structured output, programmatic or logical intermediate representations, and retrieval or knowledge-graph integration. The approach builds on formal semantics and semantic parsing while harnessing the generative and planning capabilities of LLMs. It provides a methodological and engineering path toward unifying language, knowledge, and reasoning.
1.4 Interactions Between LLMs and Algebraic Agents: AR-Agent and UR-Agent
In this book’s algebraic client architecture, the LLM plans and generates in natural language, and two kinds of algebraic agentturn the results into executable, verifiable structures.
AR-Agent (Algebraic Retrieval Agent) handles retrieval and source-based question answering. It uses RAG, GraphRAG, and reranking to turn external sources such as text, tables, and images into structured knowledge (TokenKIF) with citations.
UR-Agent (Unification Reasoning Agent) handles logical reasoning and problem solving. It converts TokenKIF and rules into clauses, solves them using SLD resolution (Horn clauses), resolution (first-order logic), or superposition (equality), and produces proof objects or answer substitutions.
The two agents share a contract: TokenKIF as the interchange format and TokenADT as the in-program data type. The three-way interaction among the LLM, agents, and program can then be implemented and replayed.
1.4.1 Dividing Responsibilities: When to Call AR or UR
Typical AR calls retrieve material, locate sources, or synthesize multiple documents where citations must identify passages, pages, or links.
Typical UR calls ask for an inference, a solution to constraints, or a proof or disproof, where the caller needs an answer substitution Θ or a proof object.
Combining agents. AR can extract facts and rules as KIF, then UR can prove a goal. Alternatively, UR can request more facts from AR when solving fails.
1.4.2 A Minimal Interaction Contract
The LLM emits a command token in the ar.* or ur.* namespace instead of unconstrained text. The agent returns a structured result and a verifiable trace.
Example requests
// Ask AR for source material
{"cmd":"ar.retrieve",
"query":"Why do residual connections in a Transformer help gradients propagate?",
"top_k":6, "schema":"KIF.v1"}
// Ask UR to perform inference
{"cmd":"ur.prove",
"goal":"∀x (Parent(x,Ann) → Ancestor(x,Ann))",
"kb":[ "...KIF rules and facts..." ],
"logic":"FOL", "strategy":"resolution"}
Example responses
// AR response: structured knowledge and citations
{"kif":[ ... ], "citations":[{"docId":"paper.pdf","page":12,"span":[341,528]}],
"trace":[{"step":"hybrid-retrieval"},{"step":"rerank"}]}
// UR response: a verifiable inference result
{"result":"proved",
"proof":{"format":"LFSC","size":1240},
"trace":[{"step":"resolve","in":[17,42],"mgu":{"x":"a"}},{"step":"empty-clause"}]}
Constraints
All responses must parse into TokenADT. AR must supply citations, and UR must be able to export a proof.
1.4.3 AR-Agent: Interface and Implementation, from Source Material to KIF
Input. A natural-language query or a subgoal planned by the LLM, optionally accompanied by a domain Profile/Schema Hint.
General first-order logic:ordered resolution or resolution with selection.
Equality:superposition (optionally with KBC completion or e-graph simplification).
Output. result ∈ {proved, disproved, unknown}, with proof | partial_trace.
Common commands. ur.prove (proof by refutation), ur.solve (Horn query), and ur.check (constraint consistency).
Engineering note. Persist the ProofToken (input clauses, unifier/MGU, and output clause) so that a small external kernel can check the proof independently.
1.4.5 On the LLM Side: Routing, Planning, and Explanation
Router. Choose the order and budget for calls to ar.*, ur.*, and tools.* according to the task’s intent and constraints.
Plan. Break a complex goal into the subgoal sequence retrieve → extract → prove/solve → render.
Render. Render kif/proof as text, tables, or code that the reader can understand, preserving the conclusion and evidence.
A practical pattern is ReAct prompting: Thought determines the route, Action issues an ar.* or ur.* command, and Observation receives KIF or a proof so planning can continue.
1.4.6 A Developer’s Checklist
Start with the contract. Write the JSON/TokenKIF contracts and TokenADT parsers for ar.* and ur.* before connecting the LLM.
Require evidence or proof. AR must return citations[], and UR must support proof export. Otherwise, fall back or mark the result “undetermined.”
Make basic strategies configurable. Parameterize AR’s top_k and reranker and UR’s selection function and ordering strategy.
Prepare for audits. Log the token trace (Plan/Action/Observation/Evidence/ProofToken) alongside cost and latency in a consistent format.
Provide fallbacks. If UR fails, add facts and rerun. If AR’s evidence is weak, request more retrieval. If neither route succeeds, return “unable to answer.”
1.4.7 A Simple Example
Question.“Prove P(f(f(a))) from the axioms P(a) and ∀x(P(x)→P(f(x))), and cite the source.”
Route. ar.retrieve locates the two axioms and their page numbers in a textbook → ur.prove performs resolution refutation → proved + proof.lfsc → render the conclusion, proof steps, and cited pages.
Comparison. If the question becomes “What motivates residual connections in Transformers? Cite your source,” the router calls ar.answer directly, without involving UR.
1.4.8 Summary
AR-Agent turns source material into structured knowledge that can be cited.
UR-Agent turns knowledge into verifiable conclusions or solutions.
The LLM handles routing and explanation.
The three cooperate under a common TokenKIF/TokenADT contract. It preserves the LLM’s strengths in expression and planning while bringing retrieval and reasoning into an executable, verifiable algebraic framework.
1.5 A Quick Example: Turning a Table of Differentiation Rules into a Runnable Program in 30 Lines of Algebraic Code
Aim. Before turning to the theory, we use a runnable example in which the structure expresses the rules to move from “code = control flow” to “code = ADT variants + pattern matching + recursion schemes.” You will see how to
turn an expression grammar directly into an ADT using sum and product types,
write each differentiation rule as a single match branch without if-else,
implement symbolic differentiation and numerical evaluation in a few dozen lines of F#,
optionally add a few lines of simplification to make the result more readable, and
use the accompanying Swift skeleton to port the example.
1.5.2 The ADT and Its Branches: Structure as Grammar, Branches as Rules
The following F# code runs as written (.NET 9 / F# 9). Expr combines sums, products, and the unit type. The function d translates each rule into a branch, and eval performs numerical evaluation.
// ===== Expression ADT =====
type Expr =
| Zero | One
| Const of double
| V of int
| E of Expr | Ln of Expr
| Sin of Expr | Cos of Expr
| Tanh of Expr | Sech of Expr
| Neg of Expr
| Plus of Expr * Expr
| Sub of Expr * Expr
| Mul of Expr * Expr
| Div of Expr * Expr
// ===== Differentiation: one branch per rule =====
let rec d (e: Expr) (i:int) : Expr =
match e with
| Zero | One | Const _ -> Zero
| V a -> if a = i then One else Zero
| E p -> Mul(E p, d p i) // (e^p)' = e^p · p'
| Ln p -> Div(d p i, p) // (ln p)' = p' / p
| Sin p -> Mul(Cos p, d p i)
| Cos p -> Mul(Neg(Sin p), d p i)
| Tanh p -> Mul(Mul(Sech p, Sech p), d p i)
| Sech p -> Mul(Neg(Mul(Sech p, Tanh p)), d p i)
| Neg p -> Neg(d p i)
| Plus(p,q) -> Plus(d p i, d q i)
| Sub(p,q) -> Sub (d p i, d q i)
| Mul(p,q) -> Plus(Mul(d p i, q), Mul(p, d q i)) // Product rule
| Div(p,q) -> Div(Sub(Mul(d p i, q), Mul(p, d q i)), Mul(q,q)) // Quotient rule
// ===== Evaluator =====
let rec eval (e:Expr) (x:double list) : double =
match e with
| Zero -> 0.0 | One -> 1.0
| Const a -> a
| V i -> x.[i]
| E p -> System.Math.Exp (eval p x)
| Ln p -> System.Math.Log (eval p x)
| Sin p -> System.Math.Sin (eval p x)
| Cos p -> System.Math.Cos (eval p x)
| Tanh p -> System.Math.Tanh (eval p x)
| Sech p -> 1.0 / System.Math.Cosh (eval p x)
| Neg p -> -(eval p x)
| Plus(p,q) -> eval p x + eval q x
| Sub(p,q) -> eval p x - eval q x
| Mul(p,q) -> eval p x * eval q x
| Div(p,q) -> eval p x / eval q x
Run the demonstration:
let y = Sub(Plus(Ln (V 1), Mul(V 1, V 0)), Sin (V 0))
// y = ln x1 + x1·x0 − sin x0
let z = d y 1
// ∂y/∂x1
printfn "z(raw) = %A" z
let v = eval y [5.0; 2.0]
// x0=5, x1=2
printfn "eval(y,[5;2]) = %.15f" v
// Result: 11.652071455223084
Each mathematical rule corresponds to one branch. Exhaustiveness checking ensures that every form is covered, and the type makes ill-formed expressions unrepresentable.
1.5.3 Corresponding Swift Code (Excerpt)
indirect enum Expr {
case zero, one
case const(Double), v(Int)
case e(Expr), ln(Expr), sin(Expr), cos(Expr), tanh(Expr), sech(Expr)
case neg(Expr), plus(Expr,Expr), sub(Expr,Expr), mul(Expr,Expr), div(Expr,Expr)
}
func d(_ e: Expr, _ i: Int) -> Expr {
switch e {
case .zero, .one, .const: return .zero
case .v(let a): return a == i ? .one : .zero
case .e(let p): return .mul(.e(p), d(p,i))
case .ln(let p): return .div(d(p,i), p)
case .sin(let p): return .mul(.cos(p), d(p,i))
case .cos(let p): return .mul(.neg(.sin(p)), d(p,i))
case .tanh(let p): return .mul(.mul(.sech(p), .sech(p)), d(p,i))
case .sech(let p): return .mul(.neg(.mul(.sech(p), .tanh(p))), d(p,i))
case .neg(let p): return .neg(d(p,i))
case .plus(let p, let q): return .plus(d(p,i), d(q,i))
case .sub (let p, let q): return .sub (d(p,i), d(q,i))
case .mul (let p, let q): return .plus(.mul(d(p,i), q), .mul(p, d(q,i)))
case .div (let p, let q): return .div(.sub(.mul(d(p,i), q), .mul(p, d(q,i))), .mul(q,q))
}
}
1.6 Suggested Reading Paths
Structure comes first throughout this book. Algebraic Code, algebraic data types, neural-network computation graphs, large language models, automatic differentiation, and executable representations of natural language all fit into this picture. This core edition offers four paths that converge, so you need not read it from cover to cover. Each path builds a shared vocabulary in Chapter 1 and brings the methods together in Chapter 8.
1.6.1 A Quick Route Through the Main Argument
Start with Chapter 1 for the token paradigm, ADTs and APM, and the division of labor between LLMs and structured interfaces. Read Chapter 3 and Chapter 4 to see how closed variants and pattern matching turn computation graphs into composable algebraic objects. Chapter 5 and Chapter 6 apply this representation to Transformers and automatic differentiation. Finish with Chapter 7 and Chapter 8, which extend the method to logical approximations of natural language and to verifiable intelligence.
Follow a single thread: language or model output is converted into structure, structures compose into programs, programs produce traceable results, and those results are checked against types, shapes, rules, and evidence. No background in category theory is required. Keep asking three questions: What shapes can the data legitimately take? Through what interface do the parts compose? What mechanism verifies the result?
1.6.2 An Engineering-First Route
Developers and architects can read Chapter 1, Chapter 4, Chapter 5, Chapter 6, Chapter 7, and Chapter 8 in that order. Chapter 4 provides a minimal cross-framework abstraction for neural networks. Chapter 5 relates it to Transformers and ONNX. Chapter 6 shows how to organize reverse computation over the same graph structure. Chapter 7 extends structured output to natural language. Read each chapter as a problem in interface design rather than a manual for a particular framework.
The engineering focus is on boundaries. The LLM must generate within a structured contract. Nodes must explicitly declare inputs, outputs, attributes, types, and shapes. Lowering must map high-level structures deterministically to a backend. Backpropagation must reuse the composability of the forward graph. Natural language must pass through a parseable intermediate representation before it enters the program. The assignments in the companion repository test whether these boundaries work in practice.
1.6.3 A Deeper Theoretical Route
Readers interested in programming languages, logic, or semantics can follow Chapter 2, Chapter 3, Chapter 6, Chapter 7, and Chapter 8. Chapter 2 uses Functor, Applicative, and Monad to describe minimal contracts for composition and effects. Chapter 3 uses sums, products, unit, and empty types to explain the syntax for constructing ADTs. Chapter 6 treats differentiation as a composable program transformation. Chapter 7 considers how finite, strongly typed structures can approximate core logical relations in natural language.
On this route, category theory is a language for checking whether compositions are valid. Look beyond terminology: Does a mapping preserve structure? Is sequencing explicit? Are side effects confined to the interface? Can a transformation be reproduced and checked?
1.6.4 LLMs and Natural Language
Readers studying models and their applications can start with Sections 1.3 and 1.4 of Chapter 1, then read Chapter 5, Chapter 7, and Chapter 8. Chapter 5 shows how the model’s own computations can be viewed as an algebraic graph. Chapter 7 shows how model output can move beyond free text to strongly typed tokens and rule structures. Chapter 8 defines the system boundary: models propose candidates, and programs and evidence determine which candidates can be accepted.
On this route, avoid equating structured output with a different JSON format. Its value lies in connecting type checking, pattern matching, function calls, execution traces, and external evidence. Once governed by these constraints, the LLM’s generative power becomes a reusable software capability.
1.6.5 Companion Repository
The exercises from the print edition are now collected at https://github.com/PanWuming/AlgebraicCode. The repository provides runnable starter code, tests and acceptance criteria, and instructions that can be updated as the toolchain changes. The book explains why the material is organized as it is and how to organize it. The repository shows how to run and verify it.
Whatever path you choose, complete at least one end-to-end assignment: convert natural language or model output to an ADT, apply a repeatable transformation, and use tests, evidence, or rules to explain why the result holds. Completing this cycle puts the book’s central method into practice.
CHAPTER 2
Long-Chain Functions, Functors, and Monads: The Syntax and Semantics of Composition
The Haskell community helped bring category theory systematically into programming languages. Moggi (Moggi, 1991) used monads to establish a categorical semantics of computation. Wadler (Wadler, 1992b, 1995) turned monads into a practical way of organizing exceptions, state, output, and nondeterminism. This influence extends well beyond mathematical curiosity. A particularly accessible example is the long-chain function: instead of supplying several arguments at once, we supply one argument at a time to a chain of functions, each returning the next. This opens a path from function composition to combinators and, ultimately, to Algebraic Code.
In the 2000s and beyond, the abstractions became more precise. Applicative (McBride & Paterson, 2008) separated the aggregation of independent steps from Monad, and arrows (Hughes, 2000) further generalized the forms composable computation could take. In the toolchain, GHC1 (GHC Development Team, 2025; Marlow & others, 2016) can automatically lower do notation to Applicative composition with ApplicativeDo, connecting the abstraction directly to syntactic sugar and optimization. Categorical abstractions such as Functor, Applicative, and Monad now appear in mainstream languages as ways to construct and compose blocks of code that handle contexts, exceptions, parallelism and concurrency, resources, and state. They complement object-oriented abstractions such as types, encapsulation, and polymorphism.
Why learn these ideas? An engineer’s perspective
Distinct semantic levels. Functor handles transformations of values, Applicative aggregates independent steps, and Monad expresses dependent sequencing or short-circuiting. Each has a small, clear role.
Refactoring. Identity, associativity, and unit laws tell us when we can fuse two maps or split a flatMap without changing behavior, giving us greater freedom to refactor.
Parallelism. Applicative naturally supports parallel aggregation of independent steps, which maps directly to Swift’s async let, Kotlin’s parZip, or Rust’s join!.
Testability. Option, Result, Task, and related contexts make effects, errors, and missing values explicit. Unit tests can use property-based testing to focus on pure transformations.
Cooperation with OO. Object-oriented design models and encapsulates data. Categorical composition assembles behavior from small units. Together they offer maintainable data structures and transparent control flow.
What this chapter covers
2.1 Long-Chain Functions. We start with currying to understand the syntax and types of reasoning in chains.
2.2 Functor.Transform values while retaining the shape. The two map laws provide safeguards for refactoring.
2.3 Applicative. When steps are independent, use mapN, zip, ap, traverse, or sequence to combine results. These operations can map directly to parallel implementations.
2.4 Monad. When steps depend on previous results or need to short-circuit, flatMap/bind flattens the computation. The laws explain which rearrangements preserve behavior.
2.5 NaturalTransformation. Functors on parameterized types.
2.6 Kleisli Categories in Programming Languages.
2.7 Pure Functions.
2.8 JAX: An Industrial-Scale Pure Functional Paradigm.
2.9 Chapter Recap: Combinator Signatures and Language Reference.
2.1 Long-Chain Functions and Code Composition
A long-chain function, or curried function, is a basic form of composition in Algebraic Code. It decomposes a function of several arguments into a chain of single-argument functions, each returning the next. In category theory this corresponds to the familiar isomorphism for exponential objects:
In type terms,
has the same expressive power as a function that takes a Cartesian product of arguments at once, . The forms and the ways they compose differ. We can extend the same rule to longer chains:
Currying converts a function of several arguments into functions that each accept one argument in turn. Partial application supplies some initial arguments to obtain a function of fewer arguments. Together they facilitate composition and pipeline notation.
Basic laws
The curry/uncurry isomorphism:
.
Associativity of function composition:
(written >> / <<).
Identity:
.
Notation 1: Function composition
Write the steps as a chain of composed pure functions:
// F#
let h = f >> g >> k // Equivalent to fun x -> k (g (f x))
Notation 2: A value pipeline
Let the value flow through the functions, following the direction of data flow:
// F#
let y = x |> f |> g |> k
Notation 3 (Swift): Trailing closures and chained higher-order functions
Swift uses trailing closures to make chained calls easier to read while retaining the semantics of pure composition:
let result = xs
.map { transform($0) }
.filter { predicate($0) }
.flatMap { expand($0) }
In this book, a curried pipeline specifically refers to the three forms of pure function chain above: currying with composition or piping, with trailing closures available for readability.
2.1.1 F#: Native Currying and Combinators
F# functions are curried by default, and arrows associate to the right:
let multiply x y = x * y // Type: int -> int -> int
let double = multiply 2 // Partial application: fix the first argument
let ten = double 5 // Evaluates to 10
assert (ten = 10)
Pipes and combinators let us write the data flow as a declarative chain:
let input = [ -2; -1; 0; 1; 2; 3 ]
let result =
input
|> List.map ((*) 2) // Partially apply (*) to multiply by 2
|> List.filter ((<) 0) // ((<) 0) is equivalent to fun x -> 0 < x
|> List.sum // Sum the elements
// result = 12
// Equivalent but more efficient: sumBy fuses map and sum, avoiding an intermediate list
let result2 =
input
|> List.filter ((<) 0)
|> List.sumBy (fun x -> x * 2)
// Combinator example: multiply by 2, then add 3
let transform = ((*) 2) >> ((+) 3)
let demo = input |> List.map transform // [-1; 1; 3; 5; 7; 9]
// Type signature of List.map (right-associative):
(*
val map : ('T -> 'U) -> 'T list -> 'U list
*)
Points to note
int -> int -> int means int -> (int -> int): the arrow is right-associative.
((*) 2) and ((+) 3) are idiomatic instances of partial application.
>> denotes function composition, applying the left function first and the right function second. It joins small transformations into larger ones.
2.1.2 Swift: Currying with Returned Functions and Trailing Closures
Swift functions are not curried by default, but returning a function gives us the same effect. Trailing closures make the resulting chains concise and readable:
// Implement currying by returning a function: multiply : Int -> (Int -> Int)
func multiply(_ x: Int) -> (Int) -> Int { { y in x * y } }
let double = multiply(2) // Partial application: fix the first argument
let ten = double(5) // 10
assert(ten == 10)
// Declarative data pipeline: map / filter / reduce
let input = [-2, -1, 0, 1, 2, 3]
let sumPositiveTimesTwo = input
.map { $0 * 2 } // Trailing closure: write the transformation after the call
.filter { $0 > 0 }
.reduce(0, +) // Add, starting from 0
// sumPositiveTimesTwo == 12
// A small higher-order apply function for use with a trailing closure
@inline(__always)
func apply<T, U>(_ value: T, using f: (T) -> U) -> U { f(value) }
let r1 = apply(5) { $0 * 2 } // 10 (trailing closure syntax)
Points to note
multiply(_:) breaks a multi-argument function into a chain of one-argument functions, equivalent to native currying in F#.
Trailing closures give map / filter / reduce a left-to-right long-chain function style.
reduce(0, +) is a direct, efficient idiom in modern Swift. Use reduce(into:) when the aggregation calls for an in-place update.
The function above accepts an integer and a transformation closure. Trailing closure syntax lets us write the transformation { $0 * 2 } after the function call, improving readability. Many Swift standard-library combinators accept trailing closures, including array map, filter, and reduce. The resulting chains read almost like natural language.
Swift also provides compositional support for error handling. The throws keyword indicates that a function may throw an error. The rethrows keyword is used for functions that compose potentially throwing closures. A function declared rethrows can propagate an error from a closure argument without independently introducing an error. For example, the signature of Collection.map in the Swift standard library is
func map<T, E>(_ transform: (Self.Element) throws(E) -> T) throws(E) -> [T] where E : Error
If transform can throw, the map call needs try and may propagate an error. If the closure cannot throw, map will not throw either. For a higher-order function marked rethrows, the caller writes try only when the supplied closure may throw. Otherwise the chain remains an ordinary functional call with no try. This carries error semantics through a composition with little syntax: mark the potentially throwing link with try without explicitly catching errors at every step.
Swift also provides try? and try! to embed throwing behavior in different contexts:
try? converts a thrown error to nil (the Optional context), letting combinators such as map and compactMap handle failure declaratively.
try! is intended for a path you know cannot fail. It makes the expression shorter but crashes if the call actually throws.
In the following example:
applyAll is a custom map-like function declared rethrows. It is an ordinary transformation when the closure is nonthrowing. Only a call that supplies a potentially throwing closure needs try.
risky simulates a computation that succeeds on even inputs and throws on odd inputs. It illustrates how try?, compactMap, and rethrows cooperate in a chain.
enum CalcError: Error { case odd(Int) }
// A potentially throwing transformation: throw for odd x, return x*10 for even x
func risky(_ x: Int) throws -> Int {
guard x % 2 == 0 else { throw CalcError.odd(x) }
return x * 10
}
// A custom higher-order function similar to map; its key annotation is rethrows:
// The caller needs try only when the supplied closure can throw.
func applyAll<T, U>(_ xs: [T], _ f: (T) throws -> U) rethrows -> [U] {
var out: [U] = []
out.reserveCapacity(xs.count)
for x in xs { out.append(try f(x)) }
return out
}
let xs = [1, 2, 3, 4]
// 1) Nonthrowing closure: no try required
let squares = applyAll(xs) { $0 * $0 } // [1, 4, 9, 16]
// 2) Throwing closure: use try; try? lifts failure into Optional
let firstDoubleEven: Int? = (try? applyAll(xs, risky))?.first
// risky(1) throws, so try? turns the whole call into nil, and first is still nil
// 3) Per-element soft failure: try? each element; compactMap drops failures
let firstSuccessful: Int? = xs.compactMap { try? risky($0) }.first
// => 20 (from 2*10): 1 is discarded and 2 succeeds
print("squares:", squares)
print("firstDoubleEven:", firstDoubleEven as Any)
print("firstSuccessful:", firstSuccessful as Any)
// 4) The same rethrows higher-order function also accepts nonthrowing functions
func bump(_ x: Int) -> Int { x + 1 }
let bumped = applyAll(xs, bump) // No try required
print("bumped:", bumped)
// 5) Another rethrows example: a value-level passthrough function
func passthrough<T, U>(_ value: T, using f: (T) throws -> U) rethrows -> U {
try f(value)
}
// Use try! when failure can be ruled out (a thrown error would crash the program)
let forced: Int = try! passthrough(8, using: risky) // 8 is even, so the call cannot throw
let safeForced: Int? = try? passthrough(8, using: risky)
print("forced:", forced, "safeForced:", safeForced as Any)
The output appears in the following order:
squares: [1, 4, 9, 16]
Calling applyAll with the nonthrowing squaring closure requires no try. Errors propagate through rethrows only when needed.
firstDoubleEven: nil
try? applyAll(xs, risky) throws on the first element, 1. The try? folds the whole call into nil, so .first is still nil. Failure is handled softly at the level of the entire chain.
firstSuccessful: Optional(20)
Here the handling is per element: xs.compactMap { try? risky($0) }. Each element gets its own try?. Failures are dropped and successes retained, so the first successful value is 2 * 10 = 20. This is per-element soft failure.
bumped: [2, 3, 4, 5]
Passing the nonthrowing bump (x+1) to applyAll again requires no try, illustrating the composability of rethrows.
forced: 80 safeForced: Optional(80)
We use try! on a path we can prove safe: 8 is even, so risky will not throw. The corresponding try? version yields Optional(80). The two illustrate the difference between asserting success and making the result optional.
This code treats error handling as a composable context. throws and rethrows determine where try is needed. try? lifts error handling into Optional so that it works with map and compactMap, while try! reduces boilerplate where safety can be proved. Long-chain functions thus extend naturally to error semantics: an error can propagate along the chain as needed, or be converted into data (Optional) and handled declaratively within the chain.
2.1.3 Summary
From a categorical perspective,
underpins the type equivalence for long-chain functions. In F#, currying and partial application come by default. Combined with |> and >>, they produce readable, composable pipelines. In Swift, returned functions and trailing closures yield the same power of composition, with map / filter / reduce supplying a data pipeline. Long-chain functions (currying) give composition its basic syntax, allowing functions to fit together in sequence. Swift and F# use devices such as trailing closures and pipe operators to support chains. Alongside mechanisms such as throws/rethrows, they offer flexible composition in both syntax and semantics. With the type system’s guarantees, we can combine separate operations into complex functionality while keeping code modular and readable.
2.2 Functor: Lifting a Value Transformation into a Context
Intuitively, a functor is a context type that supports map. It preserves the shape of the container (its structure, ordering, emptiness, and so on), mapping each element from to . Abstractly, given an ordinary function , a functor F lifts it to:
Familiar programming examples include Optional<T>, Array<T>, Result<Success, Failure>, List<'T>, and Option<'T>.
The two functor laws
Identity. map id == id. Applying the identity function leaves a container’s contents and structure unchanged.
Composition. map g >> map f == map (f ∘ g). Mapping twice in succession is equivalent to mapping the composite once.
These laws give map its pure functional reading: it introduces no side effect of its own and performs the equivalent transformation on the values.
2.2.1 Swift: Modern Idioms for Optional, Array, and Result
Optional as a minimal functor
let maybeNum: Int? = 2
let str: String? = maybeNum.map { "\($0 * 3)" } // "6"
let noneMapped: String? = (nil as Int?).map { "\($0 * 3)" } // Still nil
// Quick composition-law test (assert directly in a playground or Swift package)
func compose<A,B,C>(_ g: @escaping (B) -> C, _ f: @escaping (A) -> B) -> (A) -> C { { g(f($0)) } }
let f: (Int) -> Int = { $0 + 1 }
let g: (Int) -> Int = { $0 * 2 }
let lhs = maybeNum.map(g).map(f) // Map g, then map f
let rhs = maybeNum.map(compose(f, g)) // Map the composite once
assert(lhs == rhs)
Tip. Swift’s map accepts a KeyPath transformation, which can improve readability:
let words = ["Swift", "FSharp", "Functor"]
let counts = words.map(\.count) // [5, 6, 7]
Array.map: preserve the shape, transform the values
let nums = [1, 2, 3]
let squares = nums.map { $0 * $0 } // [1, 4, 9]
// Identity
assert(nums.map({ $0 }) == nums)
// Composition law
let h: (Int) -> Int = { $0 - 1 }
let k: (Int) -> Int = { $0 * 10 }
assert(nums.map(h).map(k) == nums.map(compose(k, h)))
Result: map successful values and use mapError for failures
enum MyError: Error { case boom }
let ok: Result<Int, MyError> = .success(3)
let asString = ok.map { "\($0)" } // .success("3")
let bad: Result<Int, MyError> = .failure(.boom)
let stillBad = bad.map { $0 * 10 } // Failure is preserved: .failure(.boom)
// An alternative: provide bimap to transform both successes and errors
extension Result {
func bimap<U, E2>(
success: (Success) -> U,
failure: (Failure) -> E2
) -> Result<U, E2> {
self.map(success).mapError(failure)
}
}
let prettyError: Result<String, String> =
bad.bimap(success: { "\($0)" }, failure: { _ in "!!!" }) // .failure("!!!")
Conceptually, Result is a bifunctor: its success and failure channels can be mapped independently. The Swift standard library provides map for success and mapError for failure. We combine them in bimap, bringing the interface closer to the categorical formulation.
2.2.2 F#: Idiomatic Composition with Option, List, and Result
F# provides its family of map functions in modules such as Option, List, and Result. Together with the |> pipe and >> combinator, they produce distinctly algebraic pipelines.
let input = [ -2; -1; 0; 1; 2; 3 ]
// List: map + filter + sum
let sumPosTimes2 =
input
|> List.map ((*) 2)
|> List.filter ((<) 0)
|> List.sum
// == 12
// More efficient fusion: avoid an intermediate list
let sumPosTimes2' =
input
|> List.filter ((<) 0)
|> List.sumBy (fun x -> x * 2)
// Option: map Some and retain None
let optX = Some 10
let mapped = optX |> Option.map (fun x -> x + 5) // Some 15
let nothing: int option = None
let stillNone = nothing |> Option.map ((*) 2) // None
// Result: map successes and use mapError for failures
let ok : Result<int, string> = Ok 3
let ok' = ok |> Result.map string // Ok "3"
let bad : Result<int, string> = Error "E"
let bad' = bad |> Result.map ((*) 10) // Still Error "E"
let badPretty = bad |> Result.mapError (fun e -> $"ERR:{e}") // Error "ERR:E"
// Composition law (using List as an example)
let f x = x + 1
let g x = x * 2
let left = input |> List.map g |> List.map f
let right = input |> List.map (f << g)
assert (left = right)
// Combinator: compose “multiply by 2” and “add 3” into one transformation
let transform = ((*) 2) >> ((+) 3)
let demo = input |> List.map transform
2.2.3 The C# Analogy: Select as a Functor Map
C# seldom uses the term “functor,” but Select on IEnumerable<T> and the Select provided for Nullable<T> by some libraries both exemplify map: preserve the structure and map only the values within it.
var nums = new[] { 1, 2, 3 };
var squares = nums.Select(x => x * x); // IEnumerable<int>: shape preserved
int? n = 2;
var s = n.Select(x => x * 3); // Available in some extension packages; none stays none
2.2.4 Summary: Embedding Transformations in a Context
Types such as Optional, Array, Result, List, and Option obey the functor laws, giving map uniform, reliable composition semantics.
Identity and composition let us refactor freely: splitting a map into two or combining two maps into one preserves behavior.
Modern idioms include:
Swift: map(\.count), map/mapError/bimap, reduce(0, +), and trailing closures.
F#: List.sumBy/Result.mapError, the >>/<< combinators, and fusion that avoids intermediate lists.
These practices consistently lift “value → value” to “value in context → value in context,” providing a foundation for declarative chaining.
2.3 Applicative: Parallelism and Aggregation for Independent Effects
Functor transforms values, and Monad handles dependent sequencing. An applicativefunctor lies between them. When steps are independent and their results only need to be combined, possibly in parallel, Applicative is the natural choice.
2.3.1 The Minimal Contract and Mental Model
Minimal contract (types)
Common equivalent forms:
The derivation relationships are:
Relationship to Monad. An Applicative can be derived from a Monad:
The converse does not hold: Applicative is weaker than Monad. It cannot express branching control that depends on a previous result. In return, it offers compositions that can be parallelized or reordered.
2.3.2 The Four Applicative Laws, with Assertion Templates
Identity
Composition
Homomorphism
Interchange
Example assertions in Swift (Optional)
// An implementation of apply for Optional
infix operator <*> : AdditionPrecedence
func <*><A,B>(f: ((A)->B)?, x: A?) -> B? { f.flatMap { g in x.map(g) } }
func pure<A>(_ x: A) -> A? { .some(x) }
let v: Int? = 3
let u: ((Int)->Int)? = { $0 + 1 }
// Identity
assert((pure({ $0 }) <*> v) == v)
// Homomorphism
assert((pure({ $0 + 1 }) <*> pure(3)) == pure(4))
Example assertions in F# (Option)
let inline (<*>) (ff: ('a->'b) option) (fa: 'a option) =
Option.bind (fun f -> fa |> Option.map f) ff
let pure x = Some x
let v = Some 3
let u = Some ((+) 1)
// Identity
assert (pure id <*> v = v)
// Homomorphism
assert (pure ((+) 1) <*> pure 3 = pure 4)
2.3.3 When to Prefer Applicative: Engineering Trade-offs
When there is no dependency between steps and we only need to combine their results, use ap/liftA2/mapN/zip.
For parallelizable work, Applicative composition can map directly to concurrency primitives (see Section 2.3.5).
For error accumulation, an Applicative such as Validated can collect all errors. A monad such as Either or Result usually short-circuits at the first error.
enum E: Error { case bad }
func map2<A,B,C>(_ ra: Result<A,E>, _ rb: Result<B,E>, _ f: (A,B)->C) -> Result<C,E> {
ra.flatMap { a in rb.map { b in f(a,b) } }
}
func zip<A,B>(_ ra: Result<A,E>, _ rb: Result<B,E>) -> Result<(A,B),E> {
map2(ra, rb, { ($0,$1) })
}
let a = Result<Int,E>.success(2)
let b = Result<Int,E>.success(3)
let s = zip(a,b).map(+)// .success(5): aggregate two independent steps
F# (custom map2 for Option/Result)
let map2 f oa ob = Option.bind (fun a -> Option.map (fun b -> f a b) ob) oa
let r = map2 (+) (Some 2) (Some 3) // Some 5
Scala (Cats)
import cats.implicits._
val r = (Option(2), Option(3)).mapN(_ + _) // Some(5)
// Error accumulation: Validated (Applicative semantics)
import cats.data.ValidatedNel
def checkName(n: String): ValidatedNel[String, String] = if (n.nonEmpty) n.validNel else "name".invalidNel
def checkAge(a: Int): ValidatedNel[String, Int] = if (a > 0) a.validNel else "age".invalidNel
case class User(n:String, a:Int)
val u = (checkName(""), checkAge(-1)).mapN(User.apply) // Invalid(NonEmptyList(name, age))
Kotlin(Arrow)
import arrow.core.*
data class User(val n:String, val a:Int)
val nameV: ValidatedNel<String,String> = "".invalidNel()
val ageV : ValidatedNel<String,Int> = (-1).invalidNel()
val user : ValidatedNel<String,User> = Validated.mapN(nameV, ageV) { n, a -> User(n,a) }
Rust
let a: Option<i32> = Some(2);
let b: Option<i32> = Some(3);
let r = a.zip(b).map(|(x,y)| x + y); // Some(5)
let ax: Result<i32,&'static str> = Ok(2);
let bx: Result<i32,&'static str> = Ok(3);
let rz = ax.zip(bx).map(|(x,y)| x + y); // Ok(5): aggregate independent results
traverse/sequence: exchanging the order of container and effect
An Applicative naturally gathers many small effects into a single organized result.
Swift (Result version)
enum Perr: Error { case bad }
func parseInt(_ s: String) -> Result<Int, Perr> {
Int(s).map(Result.success) ?? .failure(.bad)
}
func traverse<A,B>(_ xs: [A], _ f: (A)->Result<B,Perr>) -> Result<[B],Perr> {
xs.reduce(.success([])) { acc, x in
acc.flatMap { bs in f(x).map { b in bs + [b] } }
}
}
let ok = traverse([“1”,”2”,”3”], parseInt) // .success([1,2,3])
let bad = traverse([“1”,”x”,”3”], parseInt) // .failure(.bad)
sequence is the special case traverse(id), turning T<G<A>> into G<T<A>>.
Swift. Use async let to run independent asynchronous steps concurrently, then await their results together. This matches the semantics of zip/mapN.
func f() async -> Int { 2 }
func g() async -> Int { 3 }
func h(_ a:Int,_ b:Int) -> Int { a + b }
func demo() async -> Int {
async let a = f()
async let b = g()
h(await a, await b) // Independent steps → collect concurrently → combine
}
Kotlin:parZip / async {} + awaitAll.
Rust. Use join! (futures) to await results concurrently, then combine them with a function.
The rule of thumb: prefer Applicative when no step depends on an earlier one. The resulting composition can be parallelized, reordered, and tested easily.
2.3.6 Summary and Comparison
Functor transforms values.
Applicative aggregates independent effects with ap, liftA2, mapN, zip, traverse, or sequence. It allows parallel execution and reordering and can accumulate errors.
Monad expresses dependent sequencing and short-circuiting with flatMap.
A practical progression is map → mapN (Applicative) → flatMap (Monad). Move up only as the computation demands a stronger abstraction.
2.4 The Minimal Contract for a Monad
A functor tells us how to map in a context. A monad tells us how to sequence computations in a context. Possibilities such as failure or absence and requirements such as carrying state are handled behind the composition, allowing us to lay out the calculations in a single sequence.
Minimal contract (types only)
unit (also called return or pure) places an ordinary value in the minimal context.
bind (also called flatMap or >>=) passes a value from its context to the next step, which also returns a result in context. It connects the contexts correctly.
In familiar types, this becomes:
Optional:unit x == .some(x),bind == .flatMap
Array/List:unit x == [x] / list { x },bind == flatMap / collect
Result/Either:unit x == .success(x) / Right(x),bind == flatMap
2.4.1 Optional as a Monad in Swift: A Concise Semantic Match
// Try to convert the string to Int; return nil on failure
func parseInt(_ s: String) -> Int? { Int(s) }
let a: String? = “42”
let b: String? = nil
let r1: Int? = a.flatMap(parseInt) // .some(42)
let r2: Int? = b.flatMap(parseInt) // nil: short-circuits without calling parseInt
// Test the laws: left identity, right identity, and associativity (direct assertions)
func pure<T>(_ x: T) -> T? { .some(x) }
func bind<T,U>(_ m: T?, _ f: (T) -> U?) -> U? { m.flatMap(f) }
let f: (Int) -> Int? = { .some($0 + 1) }
let g: (Int) -> Int? = { .some($0 * 2) }
let x = 5
assert(bind(pure(x), f) == f(x)) // Left identity
assert(bind(.some(x), pure) == .some(x)) // Right identity
assert(bind(bind(.some(x), f), g) // Associativity
== bind(.some(x), { y in bind(f(y), g) })
Continue when a value exists, stop when it does not. Roughly, flatMap takes the A in A?, passes it to A -> B?, and produces B?.
2.4.2 Result as a Monad in Swift: Errors as a Channel
enum E: Error { case boom, oob }
func step1(_ x: Int) -> Result<String, E> {
x > 0 ? .success(“n=\(x)”) : .failure(.oob)
}
func step2(_ s: String) -> Result<Double, E> {
Double(s.dropFirst(2)).map(Result.success) ?? .failure(.boom)
}
let ok = Result<Int, E>.success(5)
let got: Result<Double, E> = ok
.flatMap(step1) // Success value "n=5"
.flatMap(step2) // -> .success(5.0)
// Short-circuit on failure: after any .failure, later steps do not run
let bad = Result<Int, E>.success(0).flatMap(step1).flatMap(step2)
// Modern idiom: bimap transforms successes and errors (bifunctor-like semantics)
extension Result {
func bimap<U, E2>(success: (Success) -> U, failure: (Failure) -> E2) -> Result<U, E2> {
self.map(success).mapError(failure)
}
}
Compare throws/try: Result makes errors explicit data, which is convenient for functional chaining. In this analogy, throws acts as language-level do notation, with bind expressed through try and unit through implicit return.
2.4.3 F#: Sequential Composition of Option, Result, and List
// Option: continue if a value exists; stop at None
let parseInt (s:string) : int option =
match System.Int32.TryParse s with
| true, v -> Some v
| _ -> None
let ratio sa sb : int option =
parseInt sa
|> Option.bind (fun a ->
parseInt sb
|> Option.bind (fun b ->
if b = 0 then None else Some (a / b)))
// List: collect is flatMap
let input = [1;2;3]
let products =
input
|> List.collect (fun x -> [x; x*10]) // Compose and flatten
// [1;10;2;20;3;30]
// Result: Result.bind chains the success channel
let step1 x = if x>0 then Ok $"n={x}" else Error "oob"
let step2 (s:string) =
match System.Double.TryParse (s.Substring 2) with
| true, v -> Ok v
| _ -> Error "boom"
let flow =
Ok 5 |> Result.bind step1 |> Result.bind step2 // Ok 5.0
// A modern DSL-style version (illustrative computation expression)
type ResultBuilder() =
member _.Bind(m,f) = Result.bind f m
member _.Return x = Ok x
let result = ResultBuilder()
let flowCE =
result {
let! s = step1 5
let! d = step2 s
return d
}
F# programs often use task { let! ... } for asynchronous work. Here let! is syntactic sugar for bind.
2.4.4 Kotlin (Arrow) and Scala (for-Comprehensions)
Kotlin with Arrow (the readable, modern either DSL)
import arrow.core.raise.either
import arrow.core.raise.ensure
fun parseInt(s: String) = s.toIntOrNull()?.right() ?: "boom".left()
val result = either {
val a = parseInt("42").bind()
ensure(a > 0) { "oob" }
a * 2
}
// Right(84)
Scala (a for-comprehension is equivalent to nested flatMap)
val res: Option[Int] = for {
a <- Option(10)
b <- Option(2)
r <- if (b == 0) None else Some(a / b)
} yield r
2.4.5 Why These Equations Matter: The Monad Laws
Left identity:
Right identity:
Associativity:
The laws let us refactor chains freely. We can merge several flatMap operations or split one apart without changing the result. This is the mathematical basis for hiding control flow behind composition.
In Haskell notation (>>=)
Left identity:
Right identity:
Associativity:
A monad is simply a stable, refactorable protocol for connecting contexts. With unit, bind, and the three laws, we can write computations involving errors, absent values, asynchronous work, environments, or state in a uniform, composable style.
2.5 Natural Transformations in Programming Languages
2.5.1 What Is a Natural Transformation in Category Theory?
A natural transformation between two functors is specified object by object. For every object it supplies a morphism , subject to naturality: for every ,
Intuitively, whether we first apply inside and then move across, or first move to and then apply , the result is the same. The transformation is compatible with the structure.
2.5.2 In Programming: Functors on Parameterized Types
In languages with parametric polymorphism (F#, Swift, Kotlin, Scala, and Haskell), a natural transformation corresponds to a polymorphic function defined for every type :
It is compatible with map:
nt (F.map f x) = G.map f (nt x).
The function performs only a structural transfer, without inspecting values of . In programming terms, it moves the contents of a container naturally from to .
2.5.3 An Engineering Definition
A natural transformation is a pure polymorphic function, forall A. F<A> -> G<A>, that moves the value in a container from F to G without inspecting the particular A.
Naturality requires compatibility with map:
nt (F.map f x) == G.map f (nt x).
2.5.4 Why It Matters
A conversion between containers that is independent of the values inside is predictable, reusable, and amenable to reasoning.
In languages with parametric polymorphism, such as F#, Swift, Kotlin, Scala, and Haskell, the signature “forall A” constrains a parametric implementation to structural operations, giving the naturality property.
2.5.5 Miniature Example 1: From Option to List
let optionToList (oa: option<'a>) : list<'a> =
match oa with Some x -> [x] | None -> []
The function works for any 'a and satisfies naturality:
optionToList (Option.map f oa) == List.map f (optionToList oa)
2.5.6 Miniature Example 2: From Swift Result to Optional, Discarding Error Information
func resultToOptional<A, E>(_ r: Result<A,E>) -> A? {
switch r { case .success(let a): return a; case .failure: return nil }
}
Again, the signature holds for all A. Swift generics and the definition of map give the naturality property.
2.5.7 Natural Transformations and Functors
A functor’s map transforms values within a container.
A natural transformation performs a structural conversion between containers.
Together they let data and computations move freely while keeping their semantics aligned.
2.6 Kleisli Categories in Programming Languages
2.6.1 The Kleisli Category
Given a monad on a category :
Objects. The same ones as in the original category: .
Morphisms. A Kleisli morphism from to is a function or morphism in . That is, it returns a in an effectful context. We write
.
Composition. Use the structure of the monad to compose morphisms (bind/flatMap in programming). Formally,
.
The Kleisli and Eilenberg–Moore categories complement one another. For every monad, they give the two extremal solutions among the adjunctions inducing it: Kleisli on the free-algebra side and Eilenberg–Moore on the algebra or model side, where the objects are -algebras (Eilenberg & Moore, 1965; Mac Lane, 1998).
2.6.2 How This Appears in Languages and APIs
The central idea is to take functions that return values in an effectful context, , treat them as first-class objects, and connect them by Kleisli composition. Here is how that looks in different languages:
Haskell
>=> and <=< implement Kleisli composition: combining (a -> m b) with (b -> m c) gives (a -> m c). The same idea underlies do notation and (>>=).
Scala
A for-comprehension desugars to map/flatMap/withFilter and can chain a sequence of A => F[B] functions with flatMap. Cats provides cats.data.Kleisli[F, A, B] directly: essentially a wrapper around A => F[B] together with combinators.
JavaScript
Chaining Promise.then composes A => Promise<B> and B => Promise<C> into A => Promise<C> via then, the monadic bind.
C# / LINQ
Query expressions desugar to Select/SelectMany, with SelectMany serving as flatMap. They allow monad-like types such as IEnumerable<T> and Task<T> to be composed in Kleisli style.
Rust
Option::and_then and Result::and_then chain functions of the form A -> Option<B> or A -> Result<B, E>, avoiding nesting.
Swift
Optional.flatMap chains functions A -> Optional<B>. Together with flatMap on collections, this is a standard use of Kleisli composition.
In short, Kleisli composition treats monad-returning functions as composable arrows. We use it almost daily under names such as flatMap, bind, and_then, SelectMany, and then. For application developers, Kleisli composition explains why these different APIs fit one pattern.
2.7 Composition Laws: Pure Functions and Effects
Pure functions
In functional semantics, a function is pure exactly when the following hold:
Its result depends only on its arguments, and it has no observable side effects. It neither reads nor writes external state nor depends on time, I/O, or randomness. This idea goes back to Backus’s algebra of programs and framework for equational reasoning (Backus, 1978).
Denotational semantics. There is a deterministic semantic mapping , and for every the result of evaluation satisfies .
Referential transparency (the substitution principle). If , then in every context . This is the standard account in texts on types and semantics (Marlow, 2010b; Pierce, 2002).
In a Cartesian closed category (CCC), we can characterize this through exponential objects and the evaluation morphism , satisfying the β and η equations (Hutton, 2016).
The intuition is that purity permits equational reasoning (Hughes, 1989).
2.7.1 Composition Laws for Pure Functions
β-law:η-law: .
Function composition: associativity and identity
.
Functor laws (mapping inside a container)
map id = id,map (g∘f) = map g ∘ map f.
Fusion and elimination of intermediate structures. Techniques such as map fusion and deforestation rely on equational reasoning (Hughes, 1989; Hutton, 2016).
With these laws, what we can read, we can rewrite and optimize.
2.7.2 What Can Impurity Break?
When a library or a piece of code hides side effects (printing, randomness, exceptions, or mutable state), the following problems arise:
Substitution may fail. If the timing of effects differs between f (g x) and (f ∘ g) x, the observable behavior can change (Pierce, 2002).
Map fusion may fail. If map performs instrumentation or increments a counter, two traversals can have different effects from one fused traversal.
Reordering is risky. Swapping independent calls need not preserve behavior when effects are present.
Once referential transparency is lost, equational rewrites lose their justification.
2.7.3 Semantic Anomalies Introduced by Floating Point
From a functional perspective, IEEE 754 floating-point arithmetic uses finite precision and rounding. Many identities from pure mathematics no longer support unrestricted equational rewrites, including those involving associativity, commutativity, and distributivity. Floating-point operations may also involve hidden state such as the rounding mode or exception flags. It is more precise to say that floating point introduces a numeric or algebraic effect that should be modeled distinctly from I/O effects.
2.7.4 A Remedy: Put Effects in Types and Compose Under the Appropriate Laws
Make effects such as failure, asynchrony, state, or logging explicit in a container M:
Governing equations: the three bind laws (left identity, right identity, and associativity).
Use: sequencing steps that have effects and depend on earlier results.
Applicative aggregation
Composition pattern: pure and <*>. The four laws are identity, composition, homomorphism, and interchange.
Use: parallel execution or aggregation of independent steps. When the order must be interchangeable, choose a commutative Applicative, such as Validation with commutative accumulation.
Functor / Traversable / Alternative:
The two Functor laws justify rewrites of mappings inside a context.
The three Traversable laws (naturality, identity, and composition) govern traversal and the collection of effects.
Alternative supplies the monoid laws for fallback choice and interacts with Applicative through laws such as distributivity and annihilation.
The conclusion is that the equations survive: we move from equations for pure functions to equations for effect containers. With the appropriate container and combinators, rewrites and optimizations can still be performed safely.
2.7.5 A Minimal Comparison in F#
Pure (fusion applies)
let f x = x + 1
let g x = x * 2
List.map f (List.map g xs) = List.map (f << g) xs
Impure (the equation breaks)
let mutable cnt = 0
let f x = cnt <- cnt + 1; x + cnt // Two maps and one fused map distribute effects differently
Explicit effects (lawful composition)
let parseInt (s:string) : Result<int,string> = ...
let recip (n:int) : Result<float,string> = ...
let (>=>) f g x = Result.bind g (f x) // Kleisli composition
let h : string -> Result<float,string> = parseInt >=> recip // Obeys the three monad laws
In short, pure functions provide referential transparency and equational reasoning. Real-world side effects should be lifted into typed effects so that they can still compose safely under the laws of Applicative, Monad, Kleisli, and Traversable, as well as Alternative.
2.8 JAX: An Industrial-Scale Pure Functional Paradigm
JAX (JAX Team, 2025) is a Python library for accelerator-oriented array computation and program transformation. It provides a NumPy-style API and makes just-in-time compilation (JIT), automatic differentiation, vectorization, and parallelization composable function transformations. Its compiler, XLA, targets CPUs, GPUs, and TPUs.
Automatic differentiation (AD). grad and higher-order derivatives are first-class facilities, alongside forward-mode jvp and reverse-mode vjp. The two modes can be chosen according to the scale and dimensions of a problem, or combined.
Vectorization (batching). vmap lifts a single-example function into one applied in batches along an axis, avoiding handwritten loops and broadcasting logic.
Multidevice parallelism (SPMD). pmap compiles a function and runs it in parallel across GPUs or TPUs. Its semantics resemble vmap, but the runtime handles replication and synchronization across devices, typically for data parallelism.
The pytree data model. JAX treats nested Python containers (lists, tuples, dictionaries, and registered types) uniformly as pytrees. Transformations such as jit, grad, vmap, and pmap can then handle structured parameters, gradients, and optimizer state transparently.
Important aspects of programming style
Keep computations as purely functional as possible: avoid mutating arrays in place and pass randomness through explicit PRNG keys. Write functions that can be composed with jit/grad/vmap/pmap. This is the idea behind JAX’s program transformations.
Controlled impurity. JAX permits boundary effects such as host_callback, I/O, and profiling. Updates can also be written in a form semantically equivalent to in-place updates while transformations preserve a pure view. Treat these facilities as controlled escape hatches that leave the primary computation’s pure functional structure intact.
Custom kernels and library calls. When calling an external CUDA or TPU kernel or a non-JAX library, use a wrapper to make state explicit or run the call outside the JIT boundary. Otherwise, the guarantees behind equational rewrites weaken.
JAX shows how pure functional programming can work at industrial scale. Build on immutable arrays and explicit state, express training and inference as composable functions, and apply grad / jit / vmap / pmap for automatic differentiation, compilation, and parallel optimization while preserving semantics. Keep side effects at controlled boundaries.
2.9 Chapter Recap: From Mapping to Sequencing, from Laws to Practice
2.9.1 Three Key Takeaways
Coherence from categories to types to code. Functor unifies value transformations, Applicative the parallel execution or aggregation of independent effects, and Monad the sequencing of dependent effects. The same structure connects the mathematics to the types and then to readable code.
Laws safeguard refactoring. map obeys identity and composition, and pure/ap and flatMap have corresponding unit and associativity laws. We can merge operations or split one into several without changing the chain’s semantics.
A practical selection guide
To transform values without flattening, use map.
To combine independent steps, use ap / liftA2 / mapN / zipWith (Applicative).
For dependent steps or short-circuiting, use flatMap / bind (Monad).
Table 2-1. Common combinator signatures (abridged)
List: List.map, List.collect (= flatMap), List.fold, and List.sumBy. Add custom map2/traverse/sequence if needed.
Syntactic sugar: computation expressions option { let! ... }, result { let! ... }, and task { let! ... }. Use the |> pipe and the >> / << combinators.
Scala (Cats ecosystem)
Basics: map, flatMap, bimap (Either), ap, mapN/tupled, and traverse/sequence.
Syntax: a for-comprehension approximates nested flatMap. Either is right-biased. Validated uses Applicative to accumulate errors.
Kotlin(Arrow)
Option/Either/Validated: map, flatMap, and mapLeft/bimap. The either { ...; bind() } DSL expresses sequential composition, mapN/zip combines results, and ensure acts as a guard.
Coroutines: suspend and either {} are often paired with parZip for parallel aggregation.
Haskell
Standard tools: fmap, pure, <*>, liftA2, >>=, join, traverse, sequence, and guard. Do notation expresses bind syntactically.
Idioms: foldMap for monoidal aggregation, newtype to define instances, and ApplicativeDo for optimization.
C# (analogous operations)
IEnumerable<T>: Select (map), SelectMany (flatMap), Zip, and Aggregate (fold). Task<T> with await resembles monadic bind, and IAsyncEnumerable<T> supports composition of asynchronous streams.
Ecosystem: libraries such as language-ext supply Map/Bind/MapLeft/BiMap/Traverse for Option/Either/Try.
Rust
Option<T>: map, and_then (= flatMap), flatten, zip, ok_or/ok_or_else (lift to Result), and transpose (Option<Result<T,E>> ↔︎ Result<Option<T>,E>).
Result<T,E>: map, and_then, and map_err. For bimap, use a crate or chain map and map_err. zip, available in newer Rust versions, combines two Ok values into a tuple.
Iterator: map, filter, flat_map, zip, fold, and try_fold. collect supports the sequence/traverse pattern, for example by collecting into Result<Vec<_>, E>.
Syntactic sugar: the ? operator returns immediately on Err or None, an early-return idiom for monadic bind. async/.await composes futures with sequencing semantics similar to bind.
GHC (the Glasgow Haskell Compiler) is the most widely used Haskell implementation. It includes a batch compiler and an interactive REPL (GHCi), with full support for Haskell 2010 and numerous built-in extensions. Its runtime system (RTS) provides lightweight threads, concurrency, parallelism, and software transactional memory (STM). The compiler desugars the source program into a typed Core language based on System FC. It then passes through STG/C-- to generate executable code using a native or LLVM backend. The ApplicativeDo extension automatically lowers independent steps in a do block to Applicative compositions, exposing opportunities for parallelism and optimization. For practical details, see the chapters on GHCi and language extensions in the GHC User’s Guide.↩︎
CHAPTER 3
ADT Variants: The Sum-of-Products Paradigm
This chapter comes down to three ideas: variants (ADTs), matching, and composition. First, we encode all mutually exclusive forms and coexisting fields of a domain precisely in its types, using sums, products, unit, and the empty type in a sum-of-products representation. Next we use algebraic pattern matching (APM) to handle the branches exhaustively. Finally, combinators such as Functor, Applicative, and Monad connect steps into verifiable pipelines. Mainstream languages support this directly. Swift enums support associated values, and a switch must cover every possible input. Kotlin’s sealed hierarchies enable compile-time exhaustiveness checks for when. F# makes selection and destructuring routine through discriminated unions (DUs) and pattern matching. Rust places variants and matching at the heart of the language with enum, match, and a rich pattern syntax.
Why emphasize the word “algebraic”? We are concerned with matching that works hand in hand with ADTs. The type system and the universal property of a sum (coproduct) connect two questions: Which branch of the sum contains the value? And how do we decompose the product in that branch? This lets the compiler check coverage and bindings and flag changes as the type evolves. The operation goes deeper than matching surface features of a string or syntax tree. Hence our specific term algebraic pattern matching.
Recursionis a natural setting for APM. With recursive expressions, syntax trees, state machines, and related structures, APM suggests a simple idiom: each rule is a branch and traversal is a fold. Write the local rule in its branch and leave walking and combining the tree to a general traversal. Section 3.3 gives a minimal example of recursion in APM and refactors handwritten recursion into composable fold/traverse operations.
ADTs and OOP complement one another. We use an architecture with a protocol-first or interface-driven outer layer and an ADT-based core. The outer layer handles mutable side effects through protocols and interfaces. The core expresses provably exhaustive domain logic with ADTs and algebraic pattern matching. Computations compose through Functor, Applicative, and Monad. This approach follows the engineering principle of favoring composition over inheritance: expose behavior through interfaces and composition, and use ADTs to encapsulate the set of possibilities. An open boundary can coexist with stronger type guarantees and testability. Swift’s protocol-oriented style and exhaustive enum matching naturally support this design.
What this chapter covers
3.1 A map of the basic forms Sum, Product, Unit, and Empty, with minimal code and categorical diagrams of products and sums as limits and colimits.
3.2 The semantics of algebraic pattern matching, a cross-language overview, and practices for exhaustiveness, guards, or-patterns, and related features.
3.3Recursion in APM: write each rule as a branch and abstract traversal as a fold or traverse.
3.4 Patterns and implementation fragments for combining ADTs and OOP. Why prefer ADTs in a closed core and interfaces at open boundaries?
3.5Further reading on the origins and evolution of ADT variants in different languages.
3.6Bringing it together: combine possibilities (ADTs), handling (APM), and flow (combinators) into a powerful construction that can be replayed, audited, and evolved.
Reading guide
If your background is in OOP, first look at the design benefits of making invalid states unrepresentable and matching exhaustively: fewer scattered if/else branches, nulls, and type checks. If functional abstractions are familiar, focus on how recursion in APM and the encapsulation of side effects behind OOP ports work together in an implementation.
3.1 Algebraic Structures: Sums, Products, Unit, and Empty, with Categorical Diagrams and Minimal Code
3.1.1 Main Ideas
Sum. A set of mutually exclusive variants: a value is either one or the other.
Product. A combination of coexisting fields: a value contains this and that together.
Unit, written (). Exactly one value. Empty (⊥/Never). No values.
Sum-of-products form. An ADT is approximately a sum of several products.
Category theory. Products and sums are simple examples of limits and colimits. The same idea gives us pullbacks and pushouts, for products subject to constraints and for gluing by identification.
Figure 3-1. Construction tree of an ADT. The Sum Type node has two variant branches. Variant1 contains a Product subtree with two fields, FieldA and FieldB. Variant2 carries no data beyond the unit value ().
The diagram illustrates the sum–product–unit structure of an ADT:
The root is the sum type of the ADT
A value of this type is either Variant1 or Variant2.
The branches are mutually exclusive. In set-theoretic terms, they form a disjoint union.
The left branch, Variant1, contains a product-type subtree
A value of Variant1 carries both fields, FieldA: TypeA and FieldB: TypeB.
This is an and relationship, as in a struct or record. The cardinalities satisfy
The right branch, Variant2, is the unit type (Unit, ())
This branch carries no data (a nullary constructor), with cardinality
The overall sum-of-products cardinality
This is the classic form ADT = sum of products.
Corresponding code examples
Swift
enum T {
case variant1(fieldA: TypeA, fieldB: TypeB) // Product
case variant2 // Unit
}
F#
type T =
| Variant1 of TypeA * TypeB // Product
| Variant2 // Unit
Closed set of branches. The type definition enumerates all possible forms. Adding a branch triggers exhaustiveness checking at pattern matches.
What cannot be represented cannot occur. An invalid combination, such as supplying FieldA without FieldB, cannot be constructed at the type level.
Simpler matching and verification. A switch or match need only handle two branches. Within the product branch, it can then process the two fields.
The diagram shows how a sum supplies the outer shell, a product supplies the inner fields, and unit supplies a nullary branch. This sum–product–unit construction encodes alternatives (sums) and coexistence (products) more directly than a base class and subclasses, and naturally supports exhaustive matching and verification.
An intuition for cardinality
Engineering significance.Invalid states cannot be constructed, for example by supplying FieldA without FieldB. Adding a variant gives a compile-time reminder at every affected switch or match.
3.1.2 Categorical Diagrams: Products, Sums, Limits, and Colimits
What are these diagrams good for? They make precise the idea that a data construction is characterized by a universal property. We can use an interface diagram to synthesize types or constraints automatically.
Figure 3-2. Universal property (limit) of the product
Any pair of arrows into factors uniquely through . Thus is characterized by the projections and unique factorization. For a programmer, this is the universal property of a record or tuple.
Figure 3-3. The sum as a colimit (coproduct)
Given , there is a unique that makes the triangles commute. This is the universal property of variants or enums: pattern matching supplies one branch for each injection.
Figure 3-4. An advanced glimpse: pullbacks and pushouts
A pullback is a product subject to the constraint , analogous to a relational join.
A pushout glues together the images of in , as in a schema merge.
When to use them. A pullback or pushout can express the domain more closely than an ordinary product or sum when the data must satisfy an alignment constraint or be merged by identification.
Table 3-1. ADT constructions and their categorical counterparts
Construction
Programming intuition
Typical syntax
Universal property
Product
Record/tuple
struct {a:A; b:B}
Limit with projections
Sum
Variant/enum
enum { inl A | inr B }
Colimit with injections
Unit
( )
Unit/unit
Terminal object
Empty
Uninhabited
Never/Void
Initial object
Pullback
Constrained product
Join condition (equality)
Limit (fiber product)
Pushout
Gluing or merging
Identification construction
Colimit (amalgamation)
Sums, products, unit, and empty in practice: eliminating invalid states
Swift example. Represent a loading state with an enum instead of keeping an optional, a Boolean, and a string as parallel flags.
enum Load<T> {
case idle
case loading
case ok(T) // Product: carry the result on success
case failed(String) // Product: carry the error on failure
}
// Use an exhaustive match: the compiler requires every state to be covered
func render(_ s: Load<Data>) {
switch s {
case .idle: print("idle")
case .loading: print("loading")
case let .ok(x): print("size:", x.count)
case let .failed(msg): print("error:", msg)
}
}
Summary
Modeling.Sums (alternatives), products (coexisting data), and unit/empty (boundary cases) let us encode 95% of business data safely and compactly in types.
Verification. Exhaustive matching and unconstructible invalid states give stronger compile-time guarantees.
Going further. When you need to impose an alignment constraint or merge by identification, consider pullbacks and pushouts. Ordinary products and sums are only zeroth-order approximations to them.
3.2 Algebraic Pattern Matching
Why the specific term algebraic pattern matching? We mean matching against an ADT (sum/product/unit/empty), governed by the type system and exhaustiveness checking. Regular-expression matching, syntax-tree traversal, and reflective type inspection are different operations. Algebraic matching turns alternatives (Sum) and coexisting fields (Product) into branch coverage and destructuring that can be checked at compile time.
Core questions at a glance
Which branch contains the value? (Sum → algebraic pattern selection)
How do we decompose the fields in that branch? (Product → algebraic pattern destructuring)
Can the compiler prove that I have coveredevery branch? (Exhaustiveness)
A Swift switch must be exhaustive. For a nonfrozen enum supplied by a library, @unknown default allows for future cases.
Kotlin checks exhaustiveness for a when over a sealed hierarchy without an else branch.
The match constructs of F#, Scala, and Rust naturally support exhaustiveness and destructuring for DUs, case classes, and enums, respectively.
C# also has property and type patterns. Without ADTs or closed hierarchies, exhaustive coverage depends on the design and is not always guaranteed by the compiler.
A categorical view of algebraic pattern matching
Pattern matching supplies a handling arrow for each injection of a sum (see the sum/coproduct diagram in Section 3.1). Given , there is a unique .
In code, for enum { Inl(A) | Inr(B) }, give match the branches Inl(a) -> ... and Inr(b) -> .... The compiler thereby constructs a unique total function. This is the programming counterpart of the universal property, a colimit, behind algebraic pattern matching.
A minimal cross-language overview
3.2.1 Swift (enum, Exhaustive Matching, and @unknown default)
enum Load<T> { case idle, loading, ok(T), failed(String) }
func render(_ s: Load<Data>) {
switch s {
case .idle: print("idle")
case .loading: print("loading")
case let .ok(x): print(x.count)
case let .failed(msg): print(msg)
@unknown default: print("future case") // Safer for system enums or nonfrozen enums
}
}
Swift requires an exhaustive switch. With @unknown default, the compiler gives a warning when a new case is added later, helping you catch omissions. Both the official language guide and community practice emphasize this.
3.2.2 F# (DUs, match, and Optional Active Patterns)
type Load<’T> = | Idle | Loading | Ok of ‘T | Failed of string
let render = function
| Idle -> printfn “idle”
| Loading -> printfn “loading”
| Ok x -> printfn “%d” x.Length
| Failed msg -> printfn “%s” msg
For more flexible partitioning or destructuring, active patterns let us define custom views that can be matched.
3.2.3 Kotlin (sealed and when Without else)
sealed interface Load<out T>
data class Ok<T>(val v: T) : Load<T>
data class Failed(val msg: String) : Load<Nothing>
object Idle : Load<Nothing>; object Loading : Load<Nothing>
fun render(s: Load<ByteArray>) = when (s) {
is Idle -> println("idle")
is Loading -> println("loading")
is Ok -> println(s.v.size)
is Failed -> println(s.msg)
// No else: the sealed hierarchy enables exhaustiveness checking
}
A sealed hierarchy makes all subclasses known at compile time, enabling exhaustiveness checks for when.
Rust checks match exhaustiveness on enums. Or-patterns, stable since Rust 1.53, can make the code more concise.
3.2.5 Scala(case class + match/Extractor)
sealed trait Load[+T]
final case class Ok[T](v: T) extends Load[T]
final case class Failed(msg: String) extends Load[Nothing]
case object Idle extends Load[Nothing]; case object Loading extends Load[Nothing]
def render(s: Load[Array[Byte]]): Unit = s match {
case Idle | Loading => println("pending")
case Ok(v) => println(v.length)
case Failed(msg) => println(msg)
}
Scala’s pattern matching works especially well with case classes and extractors (unapply).
3.2.6 C# (Property and Type Patterns Outside an ADT Setting)
static string Render(object s) => s switch
{
{ } when s is Idle or Loading => “pending”,
Ok(var v) => v.Length.ToString(),
Failed(var msg) => msg,
_ => “unknown”
};
C# provides property, type, and relational patterns. Without closed ADTs and strong exhaustiveness checking, implementations rely more on API conventions and tests.
3.2.7 Best Practices
Prefer exhaustive matching on ADTs. Avoid masking an omitted case with a catch-all default or _.
Swift: use @unknown default for nonfrozen system or third-party enums. Prefer explicit exhaustive matching for your own enums.
Kotlin: use when without else for sealed hierarchies.
Minimize partial functions. If branches should be enumerated, do not hide them in if or guard. Let the compiler audit coverage.
Use combined patterns. Or-patterns (Rust 1.53+) group equivalent branches. Scala supports alternative cases, and Swift can combine cases with case .a, .b:.
Destructure products explicitly. Express meaning through field and binding names and avoid magic indices. F# named-field patterns can improve readability.
Extend the available views. F# active patterns and Scala extractors allow algebraic matching even on external types whose structure cannot be changed.
Design for change. Public APIs may add enum cases. Common strategies include Swift’s @unknown default and Kotlin sealed hierarchies with module boundaries.
3.2.8 Reference: Elements of Algebraic Patterns
Table 3-2. Elements of algebraic patterns
Concept
Purpose
Language examples
Branch selection (sum)
Identify the variant containing a value
switch/when/match
Field destructuring (product)
Bind the fields carried by a branch
case .ok(let x) / Ok(x)
Guard or guard clause
Add a predicate to a branch
case .ok(let x) where x.count>0 / when (x>0)
Or-pattern
Combine equivalent branches
Idle | Loading(Scala/Rust)
Fallback strategy
Accommodate future enum changes
Swift @unknown default
In summary, algebraic pattern matching translates the sums and products of an ADT directly into selection and destructuring. The compiler checks coverage and the correctness of bindings. This supplies operational semantics in code for the sums, products, and unit of Section 3.1. It also underlies Section 3.4 on combining ADTs and OOP and subsequent discussions of errors, commands, and state machines.
3.3 Recursion in Algebraic Pattern Matching (APM)
Structural recursion amounts to algebraic pattern matching on an ADT. Abstract recursive calls into a homomorphism over data constructors (a fold): supply a handling arrow for each alternative of a sum, destructure products, and use unit and empty for boundary cases. The compiler can check exhaustiveness, and the structure gives a basis for termination. This is the programming counterpart of the catamorphism (fold) of recursive or initial-algebra semantics (HaskellWiki Contributors, 2025).
3.3.1 Combining Structural Recursion with APM
Sum. Write a branch for each variant (injection).
Product.Destructure all fields together in the branch.
Recursive positions. Make a recursive call for each recursive occurrence in a field, or use a fold.
Benefits. The structure is clear and easy to test. We can replace explicit recursion with a recursion scheme (catamorphism, anamorphism, or hylomorphism) for reasoning and optimization.
3.3.2 A Categorical View: Recursion as a Fold (Catamorphism)
The initial-algebra diagram. If is the initial algebra of the endofunctor , then for every -algebra there is a unique homomorphism making the diagram commute:
Figure 3-5. Categorical diagram of an initial algebra
Programming intuition. Supply a handler for each constructor, , and the system derives a single traversal (a fold). This gives handwritten recursion an algebraic formulation.
3.3.3 Minimal Implementations: Structural Recursion in Swift and F#
Swift: recursion over an enum and an optional rewrite as a fold
// Expression ADT
indirect enum Expr { case num(Int), add(Expr,Expr), mul(Expr,Expr) }
// Structural recursion: select a sum branch and destructure its product
func eval(_ e: Expr) -> Int {
switch e {
case let .num(n): return n
case let .add(a,b): return eval(a) + eval(b)
case let .mul(a,b): return eval(a) * eval(b)
}
}
// Optional: define an algebra and a fold to factor out explicit recursion
extension Expr {
func cata<T>(
_ alg: (Expr) -> ((Int)->T, (T,T)->T, (T,T)->T) -> T
) -> T {
switch self {
case let .num(n): return alg(.num(n))({ n in n }, {_,_ in fatalError()},{_,_ in fatalError()})
case let .add(a,b): return alg(.add(a,b))({ _ in fatalError() }, { x,y in x+y }, {_,_ in fatalError()})
case let .mul(a,b): return alg(.mul(a,b))({ _ in fatalError() }, {_,_ in fatalError()}, { x,y in x*y })
}
}
}
// In production, prefer a generic functor-based fold. This example simply gathers the recursive calls in one place.
F#:DU + match + rec
type Expr = Num of int | Add of Expr*Expr | Mul of Expr*Expr
let rec eval = function
| Num n -> n
| Add(a,b) -> eval a + eval b
| Mul(a,b) -> eval a * eval b
F# marks recursion explicitly with rec and uses match for algebraic destructuring. The official documentation describes pattern matching in terms of rules that align input data with logical structures and decompose the data.
When to use recursion schemes
Factor out explicit recursion. Use higher-order combinators such as cata, ana, and hylo to support rewriting, fusion optimizations, and proofs of laws.
Composability. Recursion schemes fit the generation-and-reduction pipelines of RAG and agents: build a token structure or AST, then fold it to execute.
Provability. Homomorphism and fusion laws can eliminate intermediate structures or merge traversals.
Practical reading. HaskellWiki, nLab, and tutorial blogs offer programmer-friendly explanations of a catamorphism as the unique homomorphism from an initial algebra.
An engineering checklist for recursion in APM
Prefer structural recursion. Recurse into the self-similar parts of the ADT. Avoid nonstructural recursion through arbitrary indexing or reflection.
Represent boundaries by unit or empty cases. Clear base cases ([]/() / None) make termination conditions explicit.
Pair recursion with exhaustive matching. Adding a variant gives a compile-time reminder at recursive sites that need updating, such as a Swift switch or Kotlin when.
When recursion becomes complex, consider rewriting it as a catamorphism or hylomorphism. Fusion laws remove intermediate structures, supporting optimization and equational reasoning.
Document the laws. Record your algebra and laws such as derivation and fusion as a basis for regression tests and code audits.
Summary.Recursion in APM uses algebraic matching to constrain self-calls to a unique traversal over constructors (a fold). When scale, performance, or proof demands more, move to recursion schemes and express recursive control flow as composable algebraic homomorphisms.
3.4 ADT Variants and OOP: Combining Them into a Powerful Construction
Two uses of OOP are central here:
Defining the types used to construct complex objects (the domain core)
Swift: use structs for immutable value objects and classes or actors for entities. Check invariants in factories or initializers.
C#: use record structs for value objects and classes for entities. An aggregate root exposes behavioral methods rather than raw fields.
Protocol-first boundaries: interfaces for the outside world
Put I/O, side effects, and third-party dependencies behind protocols or interfaces (Swift protocol, Kotlin/Java interface, Rust trait). The core can then depend only on abstractions and switch implementations.
In the C#/.NET driver, BsonValue is an abstract base class whose subclasses, including BsonInt32 and BsonString, encapsulate their own data. This is the class hierarchy and virtual dispatch approach. Swift-BSON instead lists every form in enum BSON { … }, using associated values for data. Consumers use an exhaustive switch. This is the ADT variant approach. The contrast gives us a concrete setting for combining ADTs and OOP.
Why favor composition over inheritance?
Inheritance can expose details of a base implementation and lock in how a design can evolve. Composition hides implementation details behind an interface.
An ADT fixes the set of possibilities in the type itself (a sum) and uses products to carry fields. Consumers match exhaustively on the branches. The compiler takes over work that would otherwise fall to runtime instanceof checks and downcasts. Swift, Kotlin, Scala, Rust, and F# all support this pattern natively.
3.4.1 The Problem: One Concept, Many Forms of Value, Illustrated with BSON
MongoDB has production-grade BSON implementations in major ecosystems including .NET, Swift, Java, Node.js, Python, and Go. A BSON value can have any one of several types. Engineers commonly model this in one of two ways:
OOP: an abstract base class and a subclass hierarchy. In the C# driver, BsonValue is the abstract base class. BsonInt32, BsonString, and the other subclasses inherit from it and encapsulate their respective data.
ADT: an enumeration of variants. In Swift, enum BSON { case int32(Int32), string(String), array([BSON]), document(BSONDocument) … } lists all possible forms in one place. Each case can carry the data specific to that form.
Both designs can express the intended semantics, but using and maintaining them feels different. An ADT fixes the set of possibilities in the type definition. A consumer covers all branches in one switch or match, and the compiler checks exhaustiveness. A class hierarchy usually relies on virtual methods or a Visitor. An omitted subclass often becomes apparent only at runtime or in tests.
3.4.2 A Minimal Comparison of the Two Models
Swift (ADT, defined in one place)
public enum BSON {
case int32(Int32)
case int64(Int64)
case string(String)
indirect case array([BSON])
case document([String: BSON])
case bool(Bool)
case double(Double)
case null
// … list the other BSON forms here
}
C# (OOP, class hierarchy)
public abstract class BsonValue { /* Common interface, virtual methods, etc. */ }
public sealed class BsonInt32 : BsonValue {
public int Value { get; }
public BsonInt32(int value) => Value = value;
}
public sealed class BsonString : BsonValue {
public string Value { get; }
public BsonString(string value) => Value = value;
}
// … define one subclass for each form
Swift lists every form in one type. In C#, the enumeration is distributed across multiple type definitions and registration points. The locality of the definition directly affects the cost of reading and changing it.
3.4.3 For Consumers: Pattern Matching, Virtual Dispatch, or Visitor
Swift: use switch for pattern matching, with exhaustiveness checked by the compiler
func bsonToString(_ v: BSON) -> String {
switch v {
case .string(let s): return s
case .int32(let n): return String(n)
case .int64(let n): return String(n)
case .double(let d): return String(d)
case .bool(let b): return String(b)
case .null: return "null"
case .array(let xs): return "[" + xs.map(bsonToString).joined(separator: ",") + "]"
case .document(let m):
let kvs = m.map { k, v in "\"\(k)\": \(bsonToString(v))" }
return "{" + kvs.joined(separator: ", ") + "}"
}
// A case added later will produce a compile-time nonexhaustive-match diagnostic here
}
C# approach 1: Virtual methods and polymorphism
public abstract class BsonValue { public abstract string Format(); }
public sealed class BsonInt32 : BsonValue {
public int Value { get; }
public override string Format() => Value.ToString();
}
// Each remaining subclass implements Format()
string s = someBsonValue.Format(); // A missing Format override in a new subclass can surface at runtime
C# approach 2: Visitor (statically detectable omissions, more boilerplate)
public interface IBsonVisitor<T> {
T Visit(BsonInt32 x);
T Visit(BsonString x);
// … one entry per subclass
}
public abstract class BsonValue { public abstract T Accept<T>(IBsonVisitor<T> v); }
public sealed class BsonInt32 : BsonValue {
public int Value { get; }
public override T Accept<T>(IBsonVisitor<T> v) => v.Visit(this);
}
// Consumer: implement a Visitor; the compiler can report an unimplemented Visit(NewSubclass)
The difference. A Visitor approaches the exhaustiveness of pattern matching, but it requires more boilerplate and costs more to extend. A switch over an ADT is direct, local, and concise.
3.4.4 Why Prefer an ADT in This Setting?
Locality of definition. All forms are enumerated together. A reader sees the possibilities at a glance, and a maintainer can evolve the definition in a single file.
Exhaustiveness. Adding a case forces the affected consumers to be updated at compile time, avoiding omissions that tests might miss until the code runs.
Make invalid states unrepresentable. For example, null and string("") are distinct forms that can be distinguished at the type level. A fragile encoding such as “TypeCode + object” is unnecessary.
Natural composition with combinators and long-chainfunctions. Combinators such as map, flatMap, and fold can be abstracted directly from an ADT, as illustrated earlier in this chapter. Data transformations follow the structure of the diagram.
Clear serialization and deserialization boundaries. A switch or match translates the wire format directly. The code mirrors the specification, making it easy to audit.
When to choose it. If the library controls the set of forms (the BSON type set is fairly stable) and consumers need strong constraints that are uniform across platforms, prefer an ADT.
3.4.5 When Class Inheritance Is Still Needed and How to Bridge the Two
Open ecosystems. If third parties must add new forms, as with plug-ins or extensible DSL semantics, a closed enum can become restrictive. An abstract base class can still provide the backbone.
Bridging strategy. Retain OOP at the external boundary and convert to an ADT internally or in the client to gain pattern matching and composition.
A conceptual bridge between C# and Swift
Class hierarchy → ADT (deserialization entry point)
Identify the concrete subclass using reflection or a factory → construct the corresponding BSON.case.
ADT → class hierarchy (calling a legacy API)
Switch on each case → instantiate the corresponding subclass → pass it to the existing interface.
For a more functional approach within .NET, define Bson directly as an F# DU. C# consumers can interoperate through pattern matching or property access. Alternatively, approximate an ADT in C# with a sealed hierarchy and switch pattern matching.
3.5 Further Reading: Origins and Evolution of ADT Variants
3.5.1 Clarifying the Terms: Abstract and Algebraic Data Types
An abstract data type comes from the tradition of data abstraction and modularization. An interface hides the representation, and invariants characterize behavior. A classic source is Liskov and Zilles’s Programming with Abstract Data Types (Liskov & Zilles, 1974).
An algebraic data typecomes from universal algebra, initial-algebra semantics, and type theory. Data are built with multiplication and addition (products and sums). Constructors supply the signature of a term algebra, and the type is the initial algebra of a polynomial functor. This is the origin of the word “algebraic” (Goguen et al., 1977; Milner et al., 1997).
In many modern languages, especially in the ML/Haskell family, ADT usually means algebraic. In this book, “ADT variants” refers to the branches or extensions of algebraic data types, including GADTs.
3.5.2 Theoretical Origins (1970s–1990s)
Initial-algebrasemantics characterizes a data type as an initial object for a given algebraic signature. Abstract data types can be characterized, and the correctness of representations proved, using initial algebras and the uniqueness of homomorphisms. This categorical and algebraic framework established the idea of data as values generated by constructors (Goguen et al., 1977).
Type-theoretic traditions including Martin-Löf type theory, the lambda calculus, and System F gave computational interpretations to parametric polymorphism and to data constructed as terms. Hindley–Milner (Damas–Milner) type inference made these constructions practical: it can infer the most general type without explicit annotations. This was crucial to the spread of ADTs and pattern matching (Damas & Milner, 1982).
Foundations in early languages
HOPE (Burstall et al., 1980) systematically introduced the combination of algebraic data types and pattern matching. It is widely regarded as a direct predecessor of the ML/Haskell line.
Standard ML (SML) included datatype and pattern matching in its formal definition (1990, revised in 1997), establishing familiar ADT syntax and static semantics (Milner et al., 1997).
The Haskell 98 Report standardized the use of data and newtype for algebraic data types, providing a reference point for many later languages (Jones, 2003).
A related line predates these languages: ALGOL 68 and Pascal already had unions or variant records (tagged unions). They lacked the constraints of typed constructors and exhaustive matching found in modern ADTs and can be viewed as their early predecessors.
3.5.3 Extensions and Refinements: GADTs and Beyond (2000s Onward)
GADTs (generalized algebraic data types) refine a constructor’s return type by allowing it to carry equalities or constraints. This makes it possible to establish properties by construction, for example in well-typed interpreters and ASTs with evidence attached to the syntax. Two treatments of semantic translation and type inference are:
Translating GADTs to System F (Weirich et al., 2006) gives a translation to System F.
Simple Unification-based Type Inference for GADTs (Vytiniotis et al., 2006) gives a practical inference method along the lines adopted by GHC.
3.5.4 Language Families and Their Variants: From Theory to Syntax
The ML/Haskell family (the home of classical ADTs)
SML, OCaml, and F# combine datatype or type with pattern matching. F# calls the construction a discriminated union, with semantics inherited from ML. Specifications and tutorials describe the rules for construction and matching (Leroy et al., 2025; Microsoft Learn, 2021a; Milner et al., 1997).
Haskell combines data/newtype with facilities for exhaustiveness checking, deriving, and type class instances (Jones, 2003).
ADT variants in contemporary mainstream languages: different syntax, common semantic roots
Rust. An enum is a first-class algebraic data type, with payloads and exhaustive matching. The official book and compiler documentation group structs, enums, and unions under the term ADTs.
Swift. Enums support associated values and exhaustive switch statements, a standard use of a sum type illustrated directly in the official documentation.
Scala. A sealed trait with case classes (or a Scala 3 enum) encodes sum × product, with exhaustiveness checked by the compiler. The Scala 3 handbook calls these ADTs explicitly.
Kotlin.Sealed classes or interfaces combined with exhaustive when expressions give the familiar ADT style a JVM form.
TypeScript.Discriminated unions and control-flow narrowing provide an ADT style on top of a structural type system.
C++17. std::variant supplies a type-safe discriminated union. Combined with std::visit for structured decomposition, it implements a sum type.
These variants differ in syntax but share sums and products as modeling primitives, together with exhaustive matching and type inference. This is the ML/Haskell tradition at work in mainstream languages.
Algebraic data types have roots in universal algebra and initial-algebra semantics and also havea natural practical connection with BNF (Backus–Naur Form). We now trace these two lines of development.
3.5.5 The Connection to Universal Algebra: Foundations of Semantics and Specification
Algebraic data types have roots in universal algebra and initial-algebra semantics and a natural practical connection with BNF (Backus–Naur Form). We now trace these two lines of development.
In universal algebra, an algebra consists of a collection of carrier sets and operations satisfying equations. The field studies abstract structures of operations and equations and general results about homomorphisms, quotients, products, and related constructions. ADTs characterize families of data through constructors (operation symbols) and equations (invariants) and thus fit this framework (Burris & Sankappanavar, 1981). math.hawaii.edu+1
Developed in the 1970s, initial-algebra semantics interprets a data type as an initial object for a signature. Its elements are terms generated by constructors, subject to equational axioms, and initiality gives representation independence. This was a key step toward rigorous semantics for abstract data types and algebraic specifications (Goguen et al., 1977).
Modern type theory and category theory often view an inductive data type as the initial algebra of a polynomial functor, the least solution of a recursive equation. This unifies constructor polynomials, initial algebras, and inductive definitions (Abbott et al., 2005).
In short, an ADT is an initial algebra for an algebraic signature, or equivalently the corresponding term algebra or free algebra. Universal algebra supplies the general vocabulary of signatures, homomorphisms, quotients, products, and equational reasoning.
3.5.6 The Connection to BNF: From Grammar to Abstract Syntax and Data
BNF is a syntax for describing syntax, or metasyntax (Wikipedia contributors, 2025). It expresses a language’s context-free grammar (CFG) as a table of production rules that determine exactly which symbol sequences are sentences of the language. Many language specifications and textbooks use BNF or a variant to present a formal grammar.
Common variants
EBNF extends BNF with notation for repetition, optionality, and grouping. It has several dialects and has been the subject of the ISO/IEC 14977 standard.
ABNF, the IETF’s Augmented BNF, is widely used in specifications for Internet protocols and data formats such as email and HTTP (Crocker & Overell, 2008).
PEG (parsing expression grammar) is a modern alternative. It uses prioritized choice and is often implemented with packrat techniques (Ford, 2004).
Compiler texts and functional programming textbooks teach a standard correspondence: map each production of the grammar to an ADT constructor. A nonterminal corresponds to an algebraic data type, alternatives (|) to a sum type, concatenation to a product or tuple, and recursive productions to recursive types. The path from BNF to an abstract syntax tree (AST) and then to an ADT definition is almost mechanical.
Tools support this mapping directly. The BNF Converter (BNFC), for example, automatically generates abstract-syntax type definitions and parsers from annotated BNF/LBNF for several target languages. In essence, it turns productions into constructors.
In summary, BNF gives the formal grammar, and an ADT gives the abstract data. Reading BNF productions as constructor signatures yields “AST = term algebra,” bringing us back to initial-algebra semantics.
From BNF to an F# ADT: a small mechanical mapping
BNF
Expr ::= Num
| Expr "+" Expr
| Expr "*" Expr
F# ADT
type Expr =
| Num of int
| Plus of Expr * Expr
| Times of Expr * Expr
3.5.7 Extending F# ADTs: Option/Result, Active Patterns, and Struct DUs
Option<'T> and Result<'T,'E> are widely used ADTs in the F# standard library. Result is a struct DU, suitable for stack-friendly use. With the Result module’s combinators it is widely used in railway-oriented1 error handling.
Active patterns turn classification or parsing into matchable views, extending matching without changing the data definition. They can be complete, partial, or parameterized. This is a distinctive F# extension to the ADT and pattern-matching ecosystem.
Struct discriminated unions. Annotate a DU with [<Struct>] to represent it as a value type on performance-sensitive paths. Restrictions apply, such as the requirement for unique field names in multicase unions.
Example: Result working with an active pattern
// Active pattern: try to parse a string as an int or a bool
let (|AsInt|AsBool|Other|) (s:string) =
match System.Int32.TryParse s, System.Boolean.TryParse s with
| (true, n), _ -> AsInt n
| _, (true, b) -> AsBool b
| _ -> Other
let parse (s:string) : Result<obj,string> =
match s with
| AsInt n -> Ok (box n)
| AsBool b -> Ok (box b)
| Other -> Error $"unrecognized: {s}"
The documentation presents active patterns as a mechanism for matching named partitions. The official documentation for Result identifies it as a struct DU and describes its companion combinator module.
3.6 Chapter Recap: Combining ADT Variants, OOP, and Combinators
Encode the set of possibilities in an ADT, put mutable side effects behind OOP ports, and compose the workflow from verifiable building blocks with map, ap, and flatMap. ADTs provide exhaustive matching and type safety, OOP provides replaceable and mockable engineering interfaces, and Functor, Applicative, and Monad make computations composable, testable, and replayable. Swift, Kotlin, F#, Rust, and Scala all have mature language and ecosystem support for this combination.
Figure 3-6. Four layers working together: long-chain functions → OOP (domain core and protocol-first boundary) → algebraic composition (ADTs and algebraic pattern matching) → combinator pipelines (Functor, Applicative, and Monad)
Why four layers?
Long-chain functions(top layer: interfaces and assembly syntax)
Use currying, partial application, and trailing closures to write chainable APIs. This facilitates protocol-first injection (Reader-style injection in the initial argument positions), and gives the subsequent OOP and ADT entry points the form of arrow chains. Swift’s trailing closures and closure rules directly support this style.
OOP (upper middle layer: objects and boundaries)
Domain core. Use classes and value types to encapsulate invariants and complex objects, including entities and value objects.
Protocol-first boundary. Put external facilities such as repositories, HTTP, LLMs, and UIs behind a protocol, interface, or trait for substitution and testing. Swift’s protocol-oriented programming (POP) and conventional interface-based OOP share this practice.
Algebraic composition (lower middle layer: structure and correctness).
Use an ADT to encode all possible forms together in a type definition (a sum of products). Consumers handle them exhaustively with algebraic pattern matching:
F# discriminated unions and pattern matching.
Kotlin sealed hierarchies and compile-time exhaustiveness checks for when.
This layer makes an uncovered case visible at compile time whenever a variant is added.
Combinator pipelines (bottom layer: assembling steps into a verifiable workflow)
Functor. Map a pure transformation over a single context (map).
Applicative. Aggregate independent effects in parallel (ap/product).
Monad. Sequence dependent steps (flatMap/bind) under laws that support reasoning. The Cats documentation gives practical definitions and APIs.
3.6.1 A Minimal Example of the Layers Working Together (Swift and Kotlin)
Swift: a command ADT, ports, and flatMap-style orchestration
// Domain ADT (sum/product)
enum Command {
case createUser(name: String, email: String)
case deleteUser(id: Int)
case resetPassword(id: Int)
}
// Port (OOP interface)
protocol UserRepo {
func exists(_ id: Int) throws -> Bool
func insert(name: String, email: String) throws
func remove(_ id: Int) throws
}
// Application service: exhaustively match an ADT inside OOP code
final class UserService {
let repo: UserRepo
init(repo: UserRepo) { self.repo = repo }
func handle(_ c: Command) throws {
switch c {
case let .createUser(name, email):
try repo.insert(name: name, email: email) // Replaceable adapter
case let .deleteUser(id):
if try repo.exists(id) { try repo.remove(id) }
case let .resetPassword(id):
// … call the LLM/email port (omitted)
}
}
}
Exhaustive matching. Adding a case produces a compile-time diagnostic for an uncovered switch branch (see the Swift enum documentation).
Replaceable ports. Inject a real or mock repository or an HTTP adapter.
Kotlin (Arrow): Either combinators treat errors as data
import arrow.core.Either
import arrow.core.flatMap
fun parseInt(s: String): Either<NumberFormatException, Int> =
if (s.matches(Regex("-?[0-9]+"))) Either.Right(s.toInt())
else Either.Left(NumberFormatException("$s is not a valid integer."))
fun reciprocal(n: Int): Either<IllegalArgumentException, Double> =
if (n != 0) Either.Right(1.0 / n) else Either.Left(IllegalArgumentException("zero"))
val res: Either<Throwable, Double> =
parseInt("42")
.flatMap { n -> reciprocal(n) } // Monad: sequence dependent steps
.map { x -> x * 100 } // Functor: pure mapping
The Arrow documentation demonstrates composition with Either.map and flatMap as a typed alternative to try-catch exception handling. Cats uses the same approach in Scala.
3.6.2 A Design Checklist for Combining the Four Layers
Use an ADT in the core. Collect the possibilities in an enum, sealed hierarchy, or DU. Do not allow data encoded as “TypeCode + Any” to cross the boundary unchecked.
Assemble workflows with combinators. Use Applicative to aggregate independent effects and Monad to sequence dependent ones. Describe data flow with pure functions and types where possible.
Favor composition and use inheritance sparingly. Compose behavior through interfaces and delegation. Avoid deep inheritance trees.
Design for evolution. If a public API may add cases, use @unknown default in Swift and control the boundaries of the sealed hierarchy in Kotlin.
Make the workflow replayable and auditable.Log the complete path from external input through the ADT and combinator pipeline to the output, enabling replay and audit.
3.6.3 Summary
An ADT defines a closed set of possibilities, OOP supplies open boundaries and substitution points, and combinators assemble data and control flow according to algebraic laws. The three are complementary:
When the external world changes, OOP ports absorb the changes.
When internal domain logic must be reliable and verifiable, use ADTs and APM.
When workflows must be composable and testable, use Functor, Applicative, and Monad.
The railway metaphor in Railway-Oriented Programming (ROP) treats Result<'T,'E> as two tracks: a success track (Ok) and a failure track (Error).↩︎
CHAPTER 4
Defining Neural Networks Across AI Frameworks with the Sweetest Layer
This chapter bridges the gap between a neural network as a mathematical object and an executable implementation with a minimal, verifiable abstraction called the sweetest layer. The high-level description specifies only structure and semantics. At the lower level, lowering mechanically translates that description into calls to a concrete operator library, here MathNet. Separating the definition of a network from its execution lets us discuss models in a common language, independently of the details of PyTorch, TensorFlow, or ONNX.
The sweetest layer has just two kinds of building block:
Primitive operators such as MatMul, Add, Sigmoid, Tanh, and Softmax perform numerical computations.
Structural combinators such as Chain, Parallel, Bundle, BigBundle, In, Select, and Sole organize data flow.
Add output semantics (Single | Multiple n | Dynamic), port contracts (shape and type constraints on inputs, outputs, and state), and minimal control-flow constructs and phase placeholders such as Iterate, Fix, and Phase(tag, Coda). We can then automatically lower a network graph through static validation → shape inference → normalization → backend selection.1
One observation runs through this chapter:
For a “simple” network such as an LSTM, the definition uniquely determines its structure and shapes. We can therefore lower it automatically and bind it directly to MathNet for execution without additional information.
For LLMs and Transformers, the phases (prefill and decode), KV-cache reads and writes, masks, positional encodings, head and dimension layouts, and even the choice of fused kernels cannot be determined from the abstract syntax alone. Correct and reliable lowering requires a profile specifying phases, shapes, layouts, caching, and operator policies so that Phase can be expanded and the implementation fixed.
Chapter outline
4.1 gives a framework-independent mathematical definition in terms of samples, parameters, function composition, and empirical risk.
4.2 uses the sweetest layer to describe forward computation and its reference rules, including output semantics and stack validation.
4.3 follows automatic lowering from the abstract definition to execution in MathNet.
4.4 works through an LSTM from its equations through the sweetest layer and automatic lowering to an executable implementation.
4.5 explains why an LLM needs a profile and identifies the minimum information it must supply.
4.6 summarizes the chapter.
Chapter 6 develops the technical details of backpropagation and automatic differentiation. Here we focus on forward semantics and the lowering mechanism itself.
4.1 A Mathematical Definition of a Deep Neural Network
4.1.1 Data and Parameters
Training examples are drawn from a distribution . Each example is a pair .
The parameter vector (or collection of tensors) is . It may be partitioned into blocks .
4.1.2 The Model as a Directed Acyclic Graph or a Composition of Functions
View the network as a computation graph built from a set of primitive operators . Each node computes
.
Equivalently, in functional notation:
Each may contain a set of parameters .
4.1.3 Loss and Empirical Risk
The loss on one example is .
The empirical risk over the entire sample is
This book keeps the mathematical and implementation layers strictly separate. The rest of the chapter describes mechanical lowering from the abstract representation (the sweetest layer) to an executable backend (MathNet).
4.2 Representing High-Level Forward Computation with Variants
Layer by layer, or node by node. Given input and parameters , compute the intermediate values in topological order to obtain .
Typical primitives
Linear transformation:
Matrix multiplication:
Hadamard:
Activation: (Sigmoid, Tanh, ReLU, and so on)
Normalization, scaling, and related operations: apply the operation as defined.
Concatenation:
Reduction:
Broadcast addition: ( is broadcast along the specified axis)
We construct networks at two levels, using primitive operators and structural combinators.
4.2.1 Primitive Operators Implemented by the Backend
The primitive operators include ShapeIx(PrimShape), Algebra(PrimAlgebra), Module(PrimModule), and Emb(PrimEmbedding).
// Enumeration used only in the Abstract layer
type Activation = Identity | ReLU | Sigmoid | Tanh | GELU
// ── Shape and indexing ──────────────────────────────────────
type PrimShape =
| Shape // Get the shape of x (lowers to NodeADT.Shape)
| Reshape //of sid:Sid // Sid identifies the shape specification (lowers to a constant shape tensor + Reshape)
| Transpose of perm:int list
| Concat of axis:int
| Split of axis:int * splits:int list option
| Unsqueeze of axes:int list
| Squeeze of axes:int list
| Slice of starts:int64 list * ends:int64 list * axes:int list * steps:int list
| Gather of axis:int
| Range of start:int64 * limit:int64 * delta:int64
| ConstantOfShape of value:float
| Cast of toType: DType // For ONNX alignment, Cast can go here with shape/indexing operations, or in the algebra group.
| Where
// ── Tensor algebra (numerical kernels) ──────────────────────
type PrimAlgebra =
| Add | Sub | Mul | Div
| MatMul
| Gemm of alpha:float * beta:float * transA:bool * transB:bool
| ReduceMean of axes:int list * keepDims:bool
| Pow | Sqrt
| Softmax of axis:int
| Act of Activation // ReLU/Sigmoid/Tanh/GELU, etc.; these can also be treated as module-level operations.
// ── Modules: common patterns built from primitive operators ─
type LinearSpec = { W:Pid; B:Pid option; transW:bool } // y = x @ W^T + b (transW=true is a common layout)
type AffineSpec = { Scale:Pid; Bias:Pid option } // y = scale ⊙ x + b (with broadcasting)
type NormSpec =
| LayerNorm of gamma:Pid * beta:Pid option * eps:float * axis:int
| RMSNorm of gamma:Pid * eps:float * axis:int
type PrimModule =
| Linear of LinearSpec
| Affine of AffineSpec
| Norm of NormSpec
// Add Dropout (a pass-through at inference), CausalMask (see the optional syntactic sugar below), and so on as needed.
// ── Embeddings: explicit semantics, usually implemented with Gather ──
type EmbeddingSpec = { Table:Pid; Axis:int } // Axis=0 for GPT-2's wte/wpe
type PrimEmbedding =
| Lookup of EmbeddingSpec // General embedding lookup
| TokenEmbedding of table:Pid // Explicit token semantics; still implemented with Gather(Axis=0)
| PosEmbedding of table:Pid // Explicit position semantics; still implemented with Gather(Axis=0)
4.2.2 Structural Combinators for Data Flow Without Numerical Computation
Bundle [n1; n2; ...] packs several inputs into one output (Single).
BigBundle [n1; ...; nk] produces k individually selectable outputs (Multiple k). Use Select i to retrieve one.
Chain [n1; n2; ...] executes the nodes in sequence. Its output is the output of the last node (Single).
Parallel [b1; ...; bk] runs k branches in parallel. Its output is Multiple k. Use In i to retrieve a branch output.
In i / Select i / Sole work as described above.
State. Feed tid reads the state from the previous time step or iteration. Bypass (port, tid) writes the new value back.
Subgraphs and mappings. SubGraph(ctx, pmap, tmap, smap, body).
Phase placeholders. Phase(tag, Coda) declares that this point is to be expanded in a particular phase. When item=Coda, it is a placeholder only. The profile determines the concrete subgraph.
Control flow. Iterate unifies the initial frame and subsequent steps of an incremental loop. Fix denotes a least fixed point.
type Node =
// Data sources
| Tensor of Tid
| Param of Pid
| ShapeParam of Sid
// Primitive operators
| ShapeIx of PrimShape
| Algebra of PrimAlgebra
| Module of PrimModule
| Emb of PrimEmbedding
// ─── Structural composition ──────────────────────────────────
/// Create a tuple of inputs for an operator with multiple arguments.
/// Output semantics: Single — one packed tuple.
/// Example: Bundle [data; shape] |> ShapeIx Reshape
| Bundle of Node list
/// Create a collection of selectable outputs.
/// Output semantics: Multiple(n) — n individually selectable outputs.
/// Example: BigBundle [node1; node2; node3] can be followed by Select 0/1/2.
| BigBundle of Node list
/// Select item i from the closest enclosing BigBundle.
/// Precondition: the enclosing construct must be a BigBundle.
/// Output semantics: Single — the selected item.
| Select of int
/// Select item i from the enclosing computation stack.
/// - Inside Parallel: select the output of branch i.
/// - Inside BigBundle: equivalent to Select i.
/// - Inside Chain: only In 0 is valid (select the last node's output).
/// Output semantics: Single — the selected item's output.
| In of int
/// Take the sole item from the enclosing output.
/// Precondition: the enclosing output semantics must be Single.
/// Output semantics: Single — pass through the enclosing construct's only output.
| Sole
// ─── Control flow ────────────────────────────────────────────
/// Execute a list of nodes in sequence.
/// Output semantics: Single — the output of the last node.
/// Data flow: node1 -> node2 -> ... -> nodeN; each node receives the previous node's output.
| Chain of Node list
/// Execute a list of nodes in parallel.
/// Output semantics: Multiple(n) — implicitly bundles the outputs of n branches.
/// Data flow: the input is copied to all branches; each branch computes independently.
/// Access: use In i to select the output of branch i.
| Parallel of Node list
// State management
| Bypass of int * Tid
| Feed of Tid
// Advanced control flow
| Iterate of IterateSpec
| Fix of FixSpec
// Subgraph with parameter, tensor, and shape mappings
| SubGraph of DefContext * ParamMap list * TensorMap list * ShapeMap list * Node
// Phase(tag, item) represents an item within a particular phase (tag).
// Convention: item = Coda denotes a placeholder that has yet to be refined into a concrete subgraph.
| Phase of string * GenericNode
// Termination
| End
// Subgraph with parameter, tensor, and shape mappings
| SubGraph of DefContext * ParamMap list * TensorMap list * ShapeMap list * Node
// Termination
| End
4.2.3 Context and Port Contracts
A network is represented as a NodeGraph:
The symbol context DefContext holds three sets of free symbols, Pids/Tids/Sids, for shape and parameter validation.
The port contract PortContract specifies name/kind/dtype/shape for inputs, outputs, and state. Its bind: Node field establishes a one-to-one correspondence between ports and values inside the graph.
Binding ports inside the graph connects external I/O to the internal representation and reduces the glue code needed for lowering.
Graph definition
/// A Node graph with its symbol table, I/O contract, and body Node
type NodeGraph = {
ctx : DefContext
io : {| inputs: PortContract list; outputs: PortContract list; states: PortContract list |}
body : Node
}
This small amount of code suffices to define useful neural networks such as LSTMs. Interpreting the variant-based definition lets us run inference and generate text.
4.3 From Abstraction to Execution: Automatic Lowering and MathNet Binding
Goal. Automatically transform a NodeGraph into an executable program implemented with MathNet.Numerics. The process has the following stages.
4.3.1 Semantic Validation
Use getOutputSemantics and validateReference to check that uses of In, Sole, and Select are valid.
Check that the output semantics of the node referenced by PortContract.bind are compatible with the port kind.
4.3.2 Shape and Type Inference
Use Sids to propagate equalities and unify broadcast constraints on symbolic shapes.
Unify operator signatures. For example, match the and dimensions of a MatMul.
4.3.3 Normalization
Reduce combinations of Parallel/BigBundle and In/Select to explicit unpacking and aggregation.
Fold constants and eliminate common subexpressions (CSE).
4.3.4 Expanding Control Flow
Iterate generates a for or while loop. Its CarryKeys annotations provide an explicit state mapping from each iteration to the next.
Fix generates a while loop that tests for convergence, or uses MaxIters for a bounded approximation.
4.3.5 Expanding Phases
For Phase(tag, Coda), substitute the corresponding subgraph if the profile supplies an implementation for tag. Otherwise the placeholder remains and cannot be lowered.
4.3.6 Selecting and Implementing Operators
Map Algebra/Module/Emb/ShapeIx to MathNet matrix, vector, and broadcasting operations.
Progressively translate Bundle/BigBundle/Chain/Parallel into local variables and expressions.
Generate a strongly typed entry point and return values from the port contracts.
For an LSTM, all six stages can be completed without additional information. For an LLM, the profile must specify phases, layouts, and caching policies at stage 5. Otherwise there is no unique lowering (see §4.5).
4.4 An LSTM from Equations to the Sweetest Layer to Executable Code
Long short-term memory (LSTM) networks were introduced in 1997 to address the difficulty of learning long-range dependencies in the presence of vanishing or exploding gradients. Memory cells and gates allow error signals to propagate stably through time, making sequence models easier to train and use (Bengio et al., 1994; Hochreiter & Schmidhuber, 1997).
Later improvements made LSTMs practical. The forget gate improved stability on long input streams (Gers et al., 2000). Bidirectional RNNs and training and labeling methods such as CTC helped bidirectional LSTMs achieve state-of-the-art results in speech and handwriting recognition (Graves et al., 2006, 2013; Schuster & Paliwal, 1997). In machine translation, the LSTM-based sequence-to-sequence encoder–decoder and its practical implementations (Sutskever et al., 2014; Y. Wu et al., 2016) enabled large-scale deployment of end-to-end neural translation.
The evolution of attention illustrates the connection to the Transformer. Attention was first proposed as an alignment mechanism for LSTM/GRU encoder–decoders (Bahdanau et al., 2015). The Transformer subsequently eliminated recurrence altogether, using self-attention to model dependencies across the sequence. This increased parallelism, accelerated training, and improved results on multiple tasks (Vaswani et al., 2017). Transformers gradually displaced LSTM-centered architectures as the prevailing approach in NLP.
In a systematic investigation of LSTM equations and variants, Greff et al. compared many LSTM variants at scale. They highlighted the importance of the forget gate and the output activation. Their study provides background for the variant-based definition and derivations that follow (Greff et al., 2017).
4.4.1 The LSTM Equations
Consider the standard equations for an LSTM cell. Given the input vector at the current time step, the previous hidden state , and the previous cell state , the forward computation for one LSTM layer is
Table 4-1. LSTM notation
Symbol
Dimensions
Meaning
Current input vector
Previous hidden state
Previous cell state
Input-to-gate weight matrix
Hidden-to-gate weight matrix
Bias vector for each gate
—
Sigmoid activation function
—
Hyperbolic tangent activation
—
Elementwise multiplication (Hadamard product)
4.4.2 Implementing an LSTM in the Sweetest Layer with Fully Automatic Lowering
The following code expresses the LSTM's data flow using only structural combinators and primitive operators. It uses no framework-specific APIs. After lowering, it maps directly to MathNet.
A common construction for the gates
open ACNN.Abstract
/// u·x + w·h + b → Act
let createGate (act: PrimModule) (wf, uf, bf: Pid*Pid*Pid) : Node =
Chain [
// Three parallel branches: Wx, Uh, b
Parallel [
Chain [ Bundle [ Param wf; Tensor (Tid "x") ]; Module PrimModule.MatMul ] // W * x
Chain [ Bundle [ Param uf; Feed (Tid "h") ]; Module PrimModule.MatMul ] // U * h_{t-1}
Param bf // b
]
// Sum the three terms
Bundle [ In 0; In 1 ]; Algebra PrimAlgebra.Add
Bundle [ Sole; In 2 ]; Algebra PrimAlgebra.Add
// Apply the activation
Module (PrimModule.Act act) // act ∈ Sigmoid | Tanh
]
The body of one LSTM layer
// Organize inputs, outputs, and state by port contract; only key fields are shown.
let lstmGraph (ctx: DefContext) (ps: {| wf:Pid; uf:Pid; bf:Pid;
wi:Pid; ui:Pid; bi:Pid;
wo:Pid; uo:Pid; bo:Pid;
wg:Pid; ug:Pid; bg:Pid;
whq:Pid; bq:Pid |}) : NodeGraph =
// Four gates computed in parallel, yielding Multiple 4
let gates =
Parallel [
createGate PrimModule.Sigmoid (ps.wf, ps.uf, ps.bf) // f_t
createGate PrimModule.Sigmoid (ps.wi, ps.ui, ps.bi) // i_t
createGate PrimModule.Sigmoid (ps.wo, ps.uo, ps.bo) // o_t
createGate PrimModule.Tanh (ps.wg, ps.ug, ps.bg) // g_t
]
// Body: update c_t and h_t from gates, then produce output y_t.
let body =
Chain [
gates
// Snapshot the four gate outputs as a selectable collection for subsequent Select i operations.
BigBundle [ In 0; In 1; In 2; In 3 ]
// c_t = f_t ⊙ c_{t-1} + i_t ⊙ g_t
Parallel [
Chain [ Bundle [ Select 0; Feed (Tid "c") ]; Algebra PrimAlgebra.Hadamard ] // f_t ⊙ c_{t-1}
Chain [ Bundle [ Select 1; Select 3 ]; Algebra PrimAlgebra.Hadamard ] // i_t ⊙ g_t
]
Bundle [ In 0; In 1 ]; Algebra PrimAlgebra.Add
Bypass (0, Tid "c") // Write back the latest c_t
// h_t = o_t ⊙ tanh(c_t)
Parallel [
Chain [ Feed (Tid "c"); Module (PrimModule.Act PrimModule.Tanh) ] // tanh(c_t)
Chain [ Select 2 ] // o_t
]
Bundle [ In 0; In 1 ]; Algebra PrimAlgebra.Hadamard
Bypass (0, Tid "h") // Write back the latest h_t
// y_t = softmax(W_hq * h_t + b_q)
Parallel [
Chain [ Bundle [ Param ps.whq; Feed (Tid "h") ]; Module PrimModule.MatMul ]
Chain [ Param ps.bq ]
]
Bundle [ In 0; In 1 ]; Algebra PrimAlgebra.Add
Module (PrimModule.Act PrimModule.Softmax)
]
{
ctx = ctx
io =
{| inputs = [ { name="x"; kind=Input; dtype=Float32; shape=Shape.ofSym "d"; bind=Tensor (Tid "x") } ]
outputs = [ { name="y"; kind=Output; dtype=Float32; shape=Shape.ofSym "q"; bind=Sole } ]
states =
[ { name="h"; kind=State; dtype=Float32; shape=Shape.ofSym "h"; bind=Feed (Tid "h") }
{ name="c"; kind=State; dtype=Float32; shape=Shape.ofSym "h"; bind=Feed (Tid "c") } ] |}
body = body
}
Act Sigmoid/Tanh/Softmax → the corresponding elementwise or normalization functions.
Parallel/Bundle/BigBundle/In/Select/Sole → normalization introduces temporaries and sequential evaluation.
Feed/Bypass → reads and writes of state variables.
Apart from the required dimensions and types, supplied by PortContract.shape/dtype and DefContext.Sids, no profile is needed.
This code illustrates a surprising aspect of organizing a program around variants. Load trained model data, use the network defined above, and enter “Sichuan University.” Here is one sample output, rendered in English:
“Sichuan University India that beauty most the beauty of immortals your perfectionism too thorough leaves me struggling even to write of hate I truly draw”
It reads like generated text, but much of it reproduces text the model has memorized. Changing controls such as temperature produces different text.
4.5 Lowering Complex LLMs: Why a Profile Is Necessary
Lowering interprets Node as the more concrete NodeForward type. The structure of NodeForward corresponds to that of Node. The next chapter defines NodeADT.
// NodeForward (execution IR): computation nodes and planning nodes in one representation
type NodeForward =
// Import external data, parameters, and constants.
| FInputTensor of outT: TensorRef * from: TensorRef // Bind an external tensor handle
| FInputParam of outT: TensorRef * from: ParamRef // Read a parameter
| FInputShape of outT: TensorRef * from: ShapeRef // A shape tensor, represented uniformly as a 1D int64 tensor
// Computation: one NodeADT and its inputs -> outputs, optionally with placement and synchronization information
| FCompute of op: NodeADT * ins: TensorRef list * outs: TensorRef list
* place: Placement option * sync: SyncSpec option
// Data movement/alignment and synchronization (optional; extend as needed)
| FCopy of dst: TensorRef * src: TensorRef * place: Placement option * sync: SyncSpec option
| FBarrier of sync: SyncSpec // Synchronization only, no data
| FFree of TensorRef // End of lifetime (memory-reuse hint)
// Structural and control-flow sugar for planning; can ultimately be flattened into a topological order
| FSeq of NodeForward list // Sequential execution
| FPar of NodeForward list // Parallel branches; data dependencies ensure safety
| FReturn of TensorRef list // Plan exit
| FCall of body: NodeForward * bindIns: (TensorRef*TensorRef) list * bindOuts: TensorRef list
| FIter of spec: IterateFSpec // Retain the existing iteration semantics
Compared with an LSTM, an LLM or Transformer introduces phase transitions, dynamic lengths, and cache layouts. The abstraction alone rarely determines a unique backend implementation. Typical difficulties include the following.
Phase differences
Prefill (a forward pass over a whole segment) and decode (autoregressive stepping) differ in operator composition, KV-cache reads and writes, masks, and positional encoding.
Use Phase(tag, Coda) as a placeholder. Before lowering, the profile expands it into a concrete subgraph.
Shapes and layouts
Specify , the kv_layout (such as [B, L, H, D] or [L, B, H, D]), mask semantics and broadcasting rules, and positional encoding settings such as RoPE or ALiBi.
Caching and loop-carried state
The profile must specify the CarryKeys of Iterate and the KV-cache mapping from present to past. Otherwise lowering cannot generate Feed/Bypass operations in the correct order.
Operator selection
Should the implementation use FlashAttention, fused GEMM, or quantized kernels? The abstract syntax cannot decide. These choices are driven by the implementation policy in the profile.
How it works
Expand Phase("Decode", Coda) as follows:
First use Feed to read the KV cache, then Module Attention (selecting the implementation from kv_layout/attn_kernel), then Bypass to write back past.
Specify Init, Body, CarryKeys, and YieldKey for Iterate. Use carry_map to generate code that passes state from the preceding iteration to the current one.
During shape inference, resolve symbolic dimensions from the profile's hyperparameters so that operations such as MatMul and Concat have concrete, implementable shapes.
In short:
For simple networks such as LSTMs, the path to execution is abstraction → lowering.
For an LLM, the path is abstraction + profile → expansion of Phase and control flow → lowering → execution.
4.6 Summary
The sweetest layer expresses forward computation with a minimal set of constructs. Primitive operators perform numerical computation, and combinators organize structure. OutputSemantics and StackSource make the use of In/Select/Sole verifiable.
NodeGraph and port contracts unify I/O with the internal graph representation, making shape and type inference and lowering straightforward.
For an LSTM, this abstraction suffices for automatic lowering to MathNet and execution.
For an LLM, correct and reliable lowering requires a profile specifying phases, shapes, layouts, caching, and operator policies.
In compiler theory, deep learning frameworks, and algebraic programming, “lowering” has much the same meaning. It is the process of progressively translating a high-level abstraction into a lower-level executable representation.↩︎
CHAPTER 5
Transformers and LLMs in Practice
Since Attention Is All You Need introduced an attention-only architecture, the Transformer has become the common backbone of modern sequence models and LLMs. GPT-2 subsequently demonstrated zero-shot and few-shot generalization through large-scale autoregressive pretraining, establishing the practical pattern of a pretraining corpus and a common backbone. Implementations such as Hugging Face's modeling_gpt2 express a block as ln_1 → attn(c_attn/c_proj) → Add → ln_2 → mlp(c_fc/gelu/c_proj) → Add. This pre-normalization structure, with two residual connections, corresponds directly to the names and topology of the exported ONNX graph.
We take three steps from the abstraction in a research paper to an executable backend.
Abstraction and alignment. Using GPT-2 as a reference, we develop the mathematics of attention, feedforward networks, and their components level by level, aligning them with the ONNX operator specifications. This book uses the ONNX 1.20 documentation.
From operators to ADTs. We classify nodes by semantics into seven groups: tensor and linear algebra, elementwise algebra, reductions and statistics, shape/layout/indexing and types, constant and tensor generation, conditional selection, and activation and normalization. For each operator we give (a) the relevant specification and opset differences, (b) precise equations, (c) typical uses in a GPT-2 graph, and (d) an F# ADT record type consistent with the Algebraic library. The result is a direct mapping from specification to code.
Execution and optimization. Using the approach from Chapter 4, we lower the ADT graph to a backend such as MathNet or custom kernels. We use system optimizations, including the I/O-aware tiling in FlashAttention, to examine practical issues in large-model inference and long-context processing.
We also consider widely used approaches to positions and context. RoPE (rotary position embedding) introduces phase structure into the representation space. ALiBi (attention with linear biases) introduces distance structure into attention scores. At the operator and ADT level, we identify the shape and profile information needed to implement them.
Think of this chapter as an operator-level blueprint for an LLM. Each entry explains a part of the ONNX specification and constrains the design of the corresponding ADT code. A common sequence—specification, equations, use, ADT—takes the Transformer as described in the literature to a computation graph that can be validated, lowered, and executed.
5.1 The Role of LLMs and Transformers
Since Attention Is All You Need (Vaswani et al., 2017) introduced the Transformer in 2017, sequence modeling has undergone a fundamental change. Attention displaced recurrence and convolution at the center of most language tasks. This enabled large-scale pretraining of large language models(LLMs) that generalize across tasks, giving rise to the general-purpose platforms and foundation-model ecosystem of contemporary AI.
Empirically, LLM performance follows fairly stable scaling laws. Loss decreases approximately as a power law with model size, training data, and training compute. The later Chinchilla results showed that, for a fixed compute budget, training is more compute-efficient when model size and training-token count grow in roughly equal proportion. These findings explain the preference for larger models, longer training runs, and better data, and give practitioners concrete guidance on design and resource allocation (Hoffmann et al., 2022; Kaplan et al., 2020).
In cross-modal generalization and practical deployment, Transformers have moved beyond text. In vision, ViT (Dosovitskiy et al., 2021) replaced convolution with attention and achieved competitive or better performance. Transferable segmentation models with prompt-based interfaces, such as SAM and SAM2, reinforced the common-backbone, task-specific-head pattern. In semantic search and question answering, RAG combines retrieval from external memory with a generative model, improving factual accuracy on knowledge-intensive tasks and making knowledge easier to update. Together these advances established LLMs and Transformers as part of AI infrastructure.
From a systems and engineering perspective, kernel and system optimizations such as FlashAttention and its successors recast the bandwidth bottleneck in attention as an I/O problem that can be optimized. They substantially accelerate training and inference and support longer contexts and larger batches. Meanwhile, rapid community development around open-source and open-weight models such as LLaMA and Mistral (A. Q. Jiang et al., 2023; Touvron, Lavril, et al., 2023; Touvron, Martin, et al., 2023) has driven advances in inference engines, scheduling, and quantization, further entrenching the ecosystem.
The quadratic complexity of attention has also motivated alternatives. Linear-time architectures such as Mamba (Gu & Dao, 2023), based on selective state space models, show promise for long sequences and high throughput. As the authors observed in their abstract, however, almost all foundation models at the time were Transformers. The technical barriers and migration costs of complete replacement are high in the near term. A more immediately practical route is to modify the structure or introduce sparsity within the Transformer architecture, for example through mixture-of-experts routing, to balance performance and efficiency.
From an industry perspective, the metaphor of AI as electricity has acquired new force in the LLM era. Just as electrification enabled advances across industries, LLMs serve as general-purpose engines for semantic processing and generation in content creation, programming, retrieval and question answering, workflow automation, and multimodal interaction. They are becoming a shared foundation for digital technology and machine intelligence. We begin with the mathematical structure of the Transformer in GPT-2 (Hugging Face, 2020; Radford et al., 2019) in §5.2. We then examine attention and its correspondence to ONNX (§5.3), trace its historical development (§5.4), and give node-level equations and ADT variant code (§5.5–§5.13).
5.2 A Mathematical Definition of the 12-Layer GPT-2 Transformer
I relate common symbols and equations to weight names, submodule names, and recurring operator patterns in Hugging Face and ONNX exports.
The following definition uses pre-layer normalization (Pre-LN) and causal self-attention.
5.2.1 Input Embeddings
Token and position embeddings
;
Here is the vocabulary size and the hidden dimension. In Hugging Face the tables are wte () and wpe (). Dropout is applied to the output.
5.2.2 Layer ()
Pre-normalization
,
.
GPT-2 defaults to (layer_norm_epsilon).
Fused QKV projection (one linear transformation produces width 3D, then splits the result):
,
Here . Hugging Face uses Conv1D(3D,D), effectively a linear layer with transposed weight storage.
Splitting into heads and scaled dot-product attention. Reshape to , where .
, .
Here is the lower-triangular mask. Hugging Face implements it with attn.bias (triangular zeros and ones) and attn.masked_bias (). The attention_mask is incorporated additively.
Merging heads and projecting the output
,
.
The pre-LN MLP branch with GELU
;
;
;
.
GELU is defined by , often approximated using tanh.
5.2.3 Output Layer
Final layer normalization and language-model head
,
The lm_head and wte share their weights.
5.2.4 Notation and Typical Shapes
is the batch size, the sequence length, the hidden dimension (768 in GPT-2 small), the head count (12), (64) the dimension per head, and the vocabulary size (50,257). The attention tensor has shape .
Table 5-1. ONNX operators, parameter names, and subgraph patterns. Hugging Face's Conv1D is effectively a linear layer with transposed weight notation and usually lowers to MatMul or Gemm in ONNX. This makes it easy to recognize in attn/c_attn, c_proj, mlp/c_fc, and mlp/c_proj.
Mathematical object
Hugging Face weight name (layer )
Typical operator or subgraph
Token embedding
wte.weight
Gather (table lookup) → add wpe
Position embedding
wpe.weight
Gather → add wte
LN1
h..ln_1.(weight | bias)
A sequence of ReduceMean/Sub/Pow/…/Div/Mul/Add (or LayerNormalization)
Fused QKV matrix
h..attn.c_attn.
(weight | bias)
MatMul | Gemm (producing width 3D in one operation), then Reshape/Split/Transpose
Causal mask
h. .attn.bias,
h..attn.masked_bias
Where/Add adds at the masked positions in the triangular pattern.
Attention output projection
h. .attn.c_proj.
(weight | bias)
MatMul | Gemm
LN2
h. .ln_2.
(weight | bias)
As for LN1
MLP intermediate projection
h. .mlp.c_fc.
(weight | bias)
MatMul | Gemm+GELU
MLP output projection
h. .mlp.c_proj.
(weight | bias)
MatMul | Gemm
Final layer normalization
ln_f.(weight | bias)
LN subgraph
LM head (weights shared with wte)
lm_head.weight == wte.weight
MatMul to dimension
Incremental decoding and past/present (KV cache)
If is supplied in the forward pass, then and , and the pass returns .
Hugging Face names the return key present. Common paired ONNX outputs are present.ℓ.(key|value), as in the logs. Their shape is usually , or with a combined axis.
5.2.5 A Compact Form Ready for Implementation
Recurrence for a complete layer
The table above gives the names of the linear weights in Attn and MLP. In ONNX, layer normalization is often decomposed into primitives. This exactly matches the pre-LN structure of Block.forward in the Hugging Face source.
Figure 5-1. ONNX computation graph for the final GPT-2 Transformer block (h.11)
Attention kernel
The c_attn projection produces width 3D in one pass, followed by Reshape/Split/Transpose. The mask combines attn.bias with the input attention_mask additively.
MLP kernel
.
Figure 5-1 uses Netron to visualize the final GPT-2 Transformer block (scope prefix transformer/h.11/...). It shows pre-normalization ln_1, the self-attention subgraph (attn/c_attn for fused QKV and attn/c_proj for projection), and the first residual Add. These are followed by ln_2, the feedforward MLP (mlp/c_fc → gelu → mlp/c_proj), and the second residual Add. On the left, the input comes from the residual output of the preceding layer, h.10. The path ends at the second Add in h.11. These names and this structure agree with Hugging Face's GPT-2 implementation.
The input comes from /transformer/h.10/.../Add.
The order within the layer is ln_1 → attn/c_attn → ... → attn/c_proj → Add → ln_2 → mlp/c_fc → gelu → mlp/c_proj → Add.
The block ends at the second Add in h.11. The complete model normally follows it with ln_f and lm_head, which are outside this figure.
5.3 Attention and Its Correspondence to GPT-2 and ONNX
Single-head scaled dot-product self-attention. Given three sets of vectors (tensors):
,;
Here is the batch size, the number of heads, the sequence length, and the dimension per head, with .
Standard attention is written as
Here combines the causal mask (the lower-triangular mask in autoregressive models) with the optional attention_mask. This is the central operation of the Transformer.
Multi-head attention (MHA) computes each head in parallel, concatenates the results along the channel dimension, and multiplies by the output projection :
In GPT-2 and ONNX, a single linear layer jointly computes (see “Fused QKV projection” below). Reshape and Transpose put the result into shape for the equation above. Common weight and node names in the exported model include the following.
h.<ℓ>.attn.c_attn.(weight|bias): ; the output is then split into Q, K, and V.
h.<ℓ>.attn.c_proj.(weight|bias):;
present.<ℓ>.key / present.<ℓ>.value: the KV cache for incremental decoding.
ln_1/ln_2: layer normalization. mlp.c_fc / mlp.c_proj: the two linear layers of the feedforward network. (Hugging Face)
Fused QKV projection. For each layer input :
In an ONNX graph this usually appears as MatMul/Gemm(+Add) → Reshape/Split/Transpose, corresponding to c_attn above. Concatenating horizontally replaces three GEMMs with one and improves efficiency.
KV caching and incremental decoding. At each autoregressive step, only the new token needs its computed. Earlier are reused and extended along the sequence dimension to produce present.<ℓ>.{key,value} for the next step. The Hugging Face documentation and community use the names past_key_values and present (Hugging Face, 2020).
Standard dense attention has time and space complexity in the sequence length (the attention matrix has size ) (Vaswani et al., 2017). This cost motivated much subsequent research.
5.4 A Brief History: From Translation Alignment to the Dominance of Attention
Additive attention(alignment) was introduced in neural machine translation. At each step the decoder computes a soft alignment over encoder hidden states, easing the bottleneck of a single fixed vector (Bahdanau et al., 2015). Luong and colleagues (Luong et al., 2015) distinguished global and local attention and compared scoring functions, helping make attention standard in sequence-to-sequence systems.
The Transformer and scaled dot-product, multi-head attention. In 2017, Attention Is All You Need replaced RNNs and CNNs with attention alone. Its scaled dot-product and multi-head mechanisms substantially improved parallelism and translation quality and provided the foundation for subsequent work.
Relative positions and longer contexts. The Transformer relies on positional information. Shaw and colleagues (Shaw et al., 2018) introduced relative position representations to improve modeling of long-range relationships. Dai and colleagues (Dai et al., 2019) introduced segment-level recurrence in Transformer-XL, considerably extending the usable context in language modeling.
Decoder-only self-attention in GPT-2. GPT-2 stacks causal self-attention layers in a decoder-only architecture, decodes incrementally, and caches keys and values (past/present). It ushered in zero-shot transfer with large autoregressive language models (Radford et al., 2019).
Cross-modal applications and vision. Attention soon spread to vision. ViT (Dosovitskiy et al., 2021) uses a Transformer alone to process images. DETR (Carion et al., 2020) uses encoder–decoder attention for end-to-end object detection.
5.5 Equations and ADT Variant Code for LLM Computation-Graph Nodes
We describe each common LLM graph node in four parts: specification, equations, typical uses in a GPT-2 graph, and correspondence with the F# ADT in AlgebraicCode. The official ONNX operator specification (ONNX Project, n.d.-b) is authoritative. When behavior changes between opsets—for example, the axes attribute in Squeeze v11 becomes a tensor input in v13—the entry identifies the specification to resolve ambiguity. Elementwise operations follow ONNX multidirectional broadcasting rules (ONNX Project, n.d.-a). Examples refer to the GPT-2 ONNX graph visualized in Netron. The nodes fall into seven semantic categories:
Constants and tensor generation (Constant, ConstantOfShape, Range).
Conditional selection (Where).
Activations and normalization (Softmax, Gelu, LayerNormalization).
For each operator we give a verifiable mathematical definition and an ADT record type (using NodeBaseInfo and related types), mapping the specification directly to its implementation.
Notation and conventions
A tensor has shape and rank .
Let be a set of axes. Negative indices are allowed. Normalize them to by using if and if . In other words:
Axis normalization: given an axis , define
Negative-index normalization: for a dimension of size ,
denotes flattening the elements. This is a convenience for reasoning and leaves the operation itself unchanged.
5.6 Tensor and Linear Algebra Nodes
5.6.1 MatMul (Matrix Multiplication)
Specification
The behavior matches numpy.matmul, including higher-dimensional batched matrix multiplication over broadcastable batch dimensions. Inputs and output are floating-point or integer tensors. The output has the input dtype. (ONNX)
Equation and shapes. If
where the batch shapes and support multidirectional broadcasting (take the larger dimension when the other is 1), then
Use in GPT-2
Computing attention weights and applying them to values
ADT correspondence and checks (MatMulNode)
type MatMulNode = {
Base: NodeBaseInfo
A: string // First matrix input
B: string // Second matrix input
Y: string // Matrix product
Attributes: AttributeADT list
}
Check that the inner dimensions match: shape(A)[-1] == shape(B)[-2].
Leading batch dimensions must support multidirectional broadcasting (see “Broadcasting in ONNX”).
5.6.2 Gemm (General Matrix Multiplication)
Semantics
Transpose and scale as specified by the attributes:
C is optional and defaults to scalar . It must support unidirectional broadcasting to . Both alpha and beta default to .
Shapes. If has shape or and has shape or , then .
Typical use in GPT-2
Projection layers and MLPs commonly implement a fully connected linear layer with Gemm(A=X, B=W^T, C=b).
ADT checks (GemmNode)
type GemmNode = {
Base: NodeBaseInfo
A: string // First matrix
B: string // Second matrix
C: string // Bias vector
Y: string // Result matrix
Alpha: float option // Scale factor alpha (attribute)
Beta: float option // Scale factor beta (attribute)
TransA: bool option // Whether to transpose A (attribute)
TransB: bool option // Whether to transpose B (attribute)
Attributes: AttributeADT list
}
TransA/TransB determine which dimensions must match for multiplication. C may be omitted, and alpha/beta default to 1. Validate C using ONNX unidirectional broadcasting.
5.7 Elementwise Algebra Nodes
5.7.1 Add, Sub, Mul, and Div (Elementwise Binary Operators)
Specification
These elementwise operations support NumPy-style multidirectional broadcasting. The output has the same numerical dtype as the inputs. From opset 14 onward, these operators also support small integer types. (ONNX) Broadcasting rules. As in NumPy, pad the shorter shape on the left with ones. A dimension of 1 can expand to the other input's corresponding dimension. (ONNX)
Equations for a broadcast output index :
Use in GPT-2
Add: residual connections and biases.
Sub: in LayerNorm.
Mul: scaling (for example, ) and applying an elementwise mask.
Div: is commonly implemented with Sqrt and Div or Mul.
ADT correspondence and checks (AddNode/SubNode/MulNode/DivNode)
type AddNode = {
Base: NodeBaseInfo
A: string // First addend
B: string // Second addend
C: string // Sum
Attributes: AttributeADT list
}
type SubNode = {
Base: NodeBaseInfo
A: string // Minuend
B: string // Subtrahend
C: string // Difference
Attributes: AttributeADT list
}
type MulNode = {
Base: NodeBaseInfo
A: string // First factor
B: string // Second factor
C: string // Product
Attributes: AttributeADT list
}
type DivNode = {
Base: NodeBaseInfo
A: string // Dividend
B: string // Divisor
C: string // Quotient
Attributes: AttributeADT list
}
Both inputs must be numerical and support multidirectional broadcasting. The output takes the broadcast shape and shares the input dtype.
For floating-point Div, implementations should propagate division by zero according to IEEE rules (Inf/NaN). Integer division depends on the runtime, and the specification does not fully prescribe rounding. In practice, avoid integer division by zero and integer scaling and convert to floating point first where possible. (ONNX)
5.7.2 Pow
Semantics (elementwise, with broadcasting)
Type rules (v15): for and , the output has the same type as the base. The allowed types for and include a wider range of integer and floating-point types.
Typical use in a GPT-2 graph. LayerNorm variance calculations often use a constant exponent Y of 2. Powers can also be computed in preparation for RMSNorm or scaling.
ADT correspondence and implementation notes
type PowNode = {
Base: NodeBaseInfo
X: string // Base
Y: string // Exponent
Z: string // Power
Attributes: AttributeADT list
}
Enforce output type = type of X during type checking. Check that broadcasting is valid by aligning and comparing trailing dimensions.
5.7.3 Sqrt
Semantics (elementwise)
Only floating-point types are supported, including bf16, fp16, fp32, and fp64.
Typical use in a GPT-2 graph
Computing the standard deviation in LayerNorm.
ADT correspondence and implementation notes
type SqrtNode = {
Base: NodeBaseInfo
X: string // Input
Y: string // Square root
Attributes: AttributeADT list
}
Require input and output to have the same shape and floating-point dtype. During constant folding, allow Pow(x, 0.5) to be normalized to Sqrt(x).
5.8 Reduction and Statistics Nodes
5.8.1 ReduceMean
Semantics
Take the mean over a given set of axes . Let . Then
Here fixes the indices of the unreduced axes, and ranges over the reduced axes. With keepdims=1, set the size of each reduced dimension to . With keepdims=0, remove those dimensions.
Typical use in a GPT-2 graph
Expanding LayerNorm:
Here A is usually the last dimension or a designated channel dimension.
ADT correspondence and implementation notes
type ReduceMeanNode = {
Base: NodeBaseInfo
Data: string // Input tensor
Reduced: string // Reduced tensor
Axes: int list option // Reduction axes (attribute)
KeepDims: bool option // Whether to retain the dimensions (attribute)
NoopWithEmptyAxes: bool option // How to handle empty axes (attribute)
Attributes: AttributeADT list
}
Static checks: allow negative axes and normalize them to [0,r-1]. When Axes=Unspecified, use NoopWithEmptyAxes to determine whether to reduce over all axes or return the input unchanged.
5.9 Shape, Layout, Indexing, and Type Nodes
5.9.1 Reshape
Specification
The shape input is a 1-D int64 tensor. It can contain -1 at most once for automatic inference and 0 with a meaning determined by allowzero.
With the default allowzero=0, a zero in shape copies the corresponding input dimension.
With allowzero=1, a zero specifies an output dimension of size zero. Combining 0 and -1 is prohibited because the result cannot be inferred uniquely.
Constraint and equation
Use in GPT-2
Reshape a linear layer's output to or .
Combine with View/Transpose/Concat to rearrange dimensions between attention and the MLP.
ADT correspondence and checks (ReshapeNode)
type ReshapeNode = {
Base: NodeBaseInfo
Data: string // Input tensor
Shape: string // New shape
Reshaped: string // Reshaped tensor
AllowZero: bool option // Whether to allow zero-sized dimensions (attribute)
Attributes: AttributeADT list
}
The Shape input must be 1-D int64. Implement -1 inference and allowzero semantics. When allowzero=1, prohibit a shape containing both 0 and -1.
5.9.2 Transpose (Permuting Dimensions)
Semantics
perm is a permutation of the axes. When omitted, it reverses their order, as in numpy.transpose.
Shape. If has shape , then has shape .
Typical use in GPT-2
Switch between and to match the axis order expected by the attention operator.
ADT checks (TransposeNode)
type TransposeNode = {
Base: NodeBaseInfo
Data: string // Input tensor
Transposed: string // Transposed tensor
Perm: int list option // Axis permutation (attribute)
Attributes: AttributeADT list
}
Perm=None reverses the axes. Otherwise, perm must have length equal to the rank and be a permutation of the axes.
5.9.3 Concat (Concatenation)
Specification
Concatenate tensors along axis. Inputs must have identical dimensions everywhere except along axis. Negative indices are allowed: axis∈[-r,r-1].
Equation and shapes. If and , then
Use in GPT-2
Split the width- output of a linear layer along its last dimension into , or concatenate the head outputs along the head or hidden dimension.
ADT correspondence and checks (ConcatNode)
type ConcatNode = {
Base: NodeBaseInfo
Inputs: string list // List of tensors to concatenate (inputs...)
ConcatResult: string // Concatenated tensor
Axis: int // Concatenation axis (attribute)
Attributes: AttributeADT list
}
Normalize Axis to .
must match across all inputs. There must be at least one input.
5.9.4 Split
Specification and opset changes
Split a tensor into segments along an axis. In v11, split was an INTS attribute. From v13, it became an optional second input (1-D int64). v18 added the num_outputs attribute, mutually exclusive with the split input. When specified, the split is uniform unless the dimension is not divisible by the count, in which case the last segment is shorter as described in the specification.
Mathematical formulation. Let and normalize axis to .
Given a vector of lengths satisfying , the outputs are
If num_outputs = m and is divisible by , each segment has length . Otherwise, according to the v18 specification, the initial segments have length , and the last takes the remainder.
Typical use in GPT-2
Split the last dimension of the c_attn fully connected output (of size ) according to to obtain .
Some exported graphs also split the head dimension or the present KV-cache dimension before rearranging the result.
ADT correspondence and implementation notes
type SplitNode = {
Base: NodeBaseInfo
Input: string // Input tensor
Split: string option // Split specification
Outputs: string list // List of output tensors (outputs...)
Axis: int option // Split axis (attribute)
NumOutputs: int option // Number of outputs (attribute)
Attributes: AttributeADT list
}
Require not (Split.IsSome && NumOutputs.IsSome) and Axis∈[-rank, rank-1].
If Split=None and NumOutputs=Some m, infer dimension a of each output statically. When division is uneven, assign the remaining length to the final segment as specified.
5.9.5 Slice
Semantics (starts, ends, axes, and steps are inputs from v10 onward)
For each axis , compute the effective triple . The defaults are axes=[0..r-1] and steps=1. Negative axes and negative start/end indices are allowed, counting from the end. A step cannot be zero. The end index is exclusive.
Shapes and indexing. Slicing and strides follow NumPy conventions. The specification gives clamping rules for negative and out-of-range indices and recommends INT_MAX/INT_MIN for the appropriate direction when the dimension length is unknown.
Typical use in GPT-2
Extract the hidden state of the final token.
Crop a window along the KV-cache or sequence dimension.
ADT checks (SliceNode)
type SliceNode = {
Base: NodeBaseInfo
Data: string // Input tensor
Starts: string // Starting indices
Ends: string // Ending indices
Axes: string option // Axes
Steps: string option // Step sizes
Output: string // Slice result
Attributes: AttributeADT list
}
Starts/Ends/Steps/Axes must be 1-D int32 or int64 tensors. starts and ends must have equal length, as must steps and axes when supplied. Require steps!=0 and normalize axes to [0,r-1].
5.9.6 Gather (Indexing Along One Axis)
Semantics
Select slices along axis (default 0) using indices. If data has rank and indices has rank , the output rank is . Indices must lie in and may be negative. (ONNX)
Shape. Replace the selected axis with the shape of indices, leaving all other axes in their original order. The documentation tabulates several examples.
Inputs
Index tensor of arbitrary rank
Axis (default ), normalized to
Output shape
Elementwise definition. For any
let
Then
In effect, the shape of indices replaces the selected axis. All other axes are preserved. Negative indices are normalized by .
Typical use in GPT-2
In a shape-processing pipeline, Shape(x) → Gather([k]) obtains the size of dimension .
Select a position along the sequence dimension, such as the final token.
ADT checks (GatherNode)
type GatherNode = {
Base: NodeBaseInfo
Data: string // Input tensor
Indices: string // Indices
Output: string // Gathered result
Axis: int option // Gather axis (attribute)
Attributes: AttributeADT list
}
Axis defaults to 0 and may be negative. Indices may have any rank and must be int32 or int64. Out-of-bounds indices are errors.
5.9.7 Shape (Returning a Shape Vector)
Semantics
The output is a 1-D int64 tensor containing the input dimension sizes. Optional start/end attributes slice the shape vector. The end is exclusive, negative axes are supported, and out-of-range bounds are clamped to . If start>end, the result is empty.
Basic function
Subintervalwith bounds (a slice of the shape vector with exclusive endpoint ):
First normalize to :
The result is
If , this is an empty vector of length zero.
Typical use in GPT-2
Together with Gather, Unsqueeze, Concat, and Reshape, this forms a shape subgraph that drives reshaping or broadcasting.
ADT checks (ShapeNode)
type ShapeNode = {
Base: NodeBaseInfo
Data: string // Input tensor
Shape: string // Shape output
Start: int option // Starting axis (attribute)
End: int option // Ending axis (attribute)
Attributes: AttributeADT list
}
The output dtype is always int64. Start and End may be negative. Clamp out-of-range bounds and handle an empty shape.
5.9.8 Unsqueeze (Inserting Dimensions of Size One at Specified Axes)
Semantics and version differences
Insert dimensions of size 1 at the positions specified by axes. In v11, axes is an attribute. From v13 onward, it is a required input (1-D int64). The axes must be distinct. The output rank equals the input rank plus |axes|. Negative axes are interpreted relative to the output rank.
A set of axes whose elements are distinct (no duplicates)
Normalization to output rank. The output rank is . For each ,
Write and denote its elements in ascending order by .
Output shape. Insert ones at the positions in :
Here maps output coordinates back to input coordinates:
Each insertion shifts subsequent indices one place to the right.
Elementwise correspondence (index injection). For every , define the injection
Then
Every index along an inserted dimension of size one coincides with its sole position.
In short, axes are interpreted relative to output rank, may be negative, and must be distinct. The operation injects input indices into a higher-rank index space, fixing each inserted position to 0 (length 1).
Typical use in GPT-2
Increase the rank of a scalar or vector for broadcasting, for instance by turning scalar into .
ADT checks (UnsqueezeNode)
type UnsqueezeNode = {
Base: NodeBaseInfo
Data: string // Input tensor
AxesInput: string option // Input tensor specifying the axes to insert
AxesAttr: int64 list option // Axes supplied directly as an attribute
Expanded: string // Expanded tensor
Attributes: AttributeADT list
}
Support either AxesInput (v13+) or AxesAttr (v11). Reject a specification that supplies both.
5.9.9 Squeeze (Removing Axes of Size One)
Specification and opset differences
Purpose. Remove dimensions of size . If axes is given, remove only the specified axes of size . It is an error if such an axis has size other than . From opset 13 onward, axes is an optional second input (a 1-D int64 tensor). Earlier versions, including v1 and v11, use an axes attribute. Omitting axes removes all dimensions of size one.
Mathematical definition
Given :
Implicit mode (axes omitted):
Explicit axis set :
where .
Properties on the domain of definition
Volume preservation: .
Idempotence: .
No reordering: the order of the remaining axes is unchanged.
Typical uses in a GPT-2 graph
A shape pipeline often contains Shape → Gather → (optional) Squeeze. It squeezes shape(x)[k] from shape (1) (or [*,1]) to obtain a scalar parameter for Reshape, Expand, or a subsequent operator.
Near attention or LayerNorm, remove a superfluous batch or head dimension of length one to keep broadcasting and alignment straightforward.
ADT correspondence
type AxesSpec =
| AllImplicit // No axes provided: remove all size-one dimensions
| Attr of int list // opset <= 12: axes from the attribute
| Input of string // opset >= 13: name of the axes tensor (1-D int64)
type SqueezeNode = {
Base : NodeBaseInfo
Data : string // Input tensor name
Axes : AxesSpec
Squeezed : string // Output tensor name
Opset : int option
Attributes : AttributeADT list
}
AllImplicit implements the rule that omitting axes removes all dimensions of size one.
For Input of string, verify that the tensor is 1-D int64. Negative indices are supported in the range [-r, r-1].
Implementation identities and assertions for static checking and simplification
Squeeze is idempotent:
.
Volume is conserved whenever the operation is defined:
.
5.9.10 Cast (Data Type Conversion)
Specification
Purpose. Convert each input element from type T₁ to type T₂ while preserving the shape. The to attribute specifies the target as a TensorProto enumeration value. Casting from a complex type is unsupported, as is casting to a complex type.
Recent specifications give more detail for the float8 family and microscaling (MX). For float8 targets, including e8m0, they introduce saturate and, for e8m0, round_mode. With saturate=1, out-of-range values are clamped to the extrema. With saturate=0, some cases yield NaN or Inf. Tables specify the handling of special values.
Mathematical formulation
Let be the elementwise conversion function, including rounding, truncation, and clamping. Then
,
For a float8 target with saturate=1, there is a threshold such that
Note. The composition law for casts can fail: error and clamping in two successive casts can differ from a single direct cast.
Typical uses in a GPT-2 graph
Convert a Boolean or integer attention mask to floating point and combine it with an additive mask before Softmax. Masked scores receive a large negative value (for example, −104 to −10⁹) or negative infinity.
Normalize types or align them with an operator, for example int64 → int32 or float16/bfloat16 ↔︎ float32 to suit a kernel. These patterns are common in exported graphs. The exact placement of Cast depends on the exporter version.
ADT correspondence
type CastNode = {
Base: NodeBaseInfo
Input: string // Input tensor
Output: string // Converted tensor
To: ACNN.Abstract.DType // Target data type (attribute)
Attributes: AttributeADT list
}
When building or validating the graph, check the following:
dtype(Output)=To and shape(Output)=shape(Input).
If To is in the float8 family, allow saturate/round_mode, which may be included in Attributes.
Reject complex input types.
Implementation identities and assertions for static checking and simplification
Cast preserves shape:
.
Two successive casts need not equal a direct cast because of rounding error or clamping:
in general.
5.10 Constant and Tensor Generation Nodes
5.10.1 Constant (Constant Tensor)
Specification
Purpose. Produce a constant tensor. Exactly one value attribute must be provided: value (a tensor), sparse_value (a sparse tensor), or a member of the value_* family, such as value_float(s), value_int(s), or value_string(s), convenient for scalar or 1-D values. Recent versions have restated this requirement and expanded the value_* family.
The specified attribute determines the output type T. The node takes no inputs, and both shape and element values can be inferred statically.
Mathematical formulation
Here is the single attribute chosen from those allowed, for example value for a whole tensor or value_float for a scalar.
Typical uses in a GPT-2 graph
Small numerical and shape constants such as 0, 1, -1, and 2 occur in Shape/Gather/Squeeze/Unsqueeze/Reshape pipelines.
The LayerNorm ε constant, for example 10⁻⁵.
Scale and offset constants, incorporated into the graph by subsequent Mul/Add operations.
ADT correspondence
type ConstantNode = {
Base: NodeBaseInfo
Output: string // Constant tensor
Value: obj option // Constant value (attribute)
ValueFloat: float option // Floating-point constant (attribute)
ValueInt: int option // Integer constant (attribute)
Attributes: AttributeADT list
}
At validation time or runtime, enforce mutual exclusivity with exactlyOne(Value, ValueFloat, ValueInt, …), then derive dtype(Output) and shape(Output). Extend the ADT with value_strings/value_ints/value_floats where the 1-D cases are needed.
Implementation identities and assertions for static checking and simplification
Constant folding. Constants passed through a chain of pure operators such as Add/Mul can be folded at compile time. A shape pipeline such as Constant → (Concat/Gather/Unsqueeze) can be evaluated in advance.
5.10.2 ConstantOfShape
Specification
Input: a 1-D int64 shape tensor. It may be empty, in which case the output is a scalar.
The optional value attribute is a single-element tensor specifying the fill value and dtype. The default is float32 zero. All dimensions must be nonnegative. The output has the shape specified by the input.
Mathematical formulation
If the input shape is and the attribute supplies the scalar (or the default ), then
Typical use in GPT-2
Construct a tensor filled with zeros or another constant for a mask, an padding value, or a shape-driven operation combined with Expand or Where.
ADT correspondence and implementation notes
type ConstantOfShapeNode = {
Base: NodeBaseInfo
Input: string // Shape tensor
Output: string // Output tensor
Value: obj option // Fill value (attribute)
Attributes: AttributeADT list
}
Static checks: every entry of the shape vector must be nonnegative. When Value=None, infer dtype=Float32 and value=0. (ONNX)
5.10.3 Range
Semantics (from opset 11). The inputs start, limit, and delta are scalars of the same type . The output is a 1-D tensor. Its number of elements is
The upper bound is exclusive. If the step points away from the interval, . The specification uses delta as a divisor, so implementations require , a constraint implied by the formula and function body.
Typical use in a GPT-2 graph. Rare in standard GPT-2 exports, Range sometimes appears in function expansions such as RMSNorm or test models, or in shape construction, to generate evenly spaced indices.
ADT correspondence
type RangeNode = {
Base: NodeBaseInfo
Start: string // Starting value
Limit: string // Exclusive limit
Delta: string // Step size
Output: string // Range tensor
Attributes: AttributeADT list
}
When building or checking the graph, assert the following:
Start, Limit, and Delta are all scalars (rank=0).
Their dtypes match and belong to {float,double,int16,int32,int64}.
Delta ≠ 0;
Output is 1-D, and its length can be inferred statically from the equation above.
5.11 Conditional Selection Nodes
5.11.1 Where
Specification
Elementwise ternary selection: condition is bool. NumPy-style multidirectional broadcasting gives the output the broadcast shape of condition, X, and Y. X, Y, and the output share a type. (ONNX)
Mathematical formulation
For each output index after broadcasting,
For numerical types this can also be written as , an equivalent expression for derivation that leaves the specification unchanged.
Typical use in GPT-2
Use the attention mask to select or for scores before softmax.
Replace values at padding positions with a constant.
ADT correspondence and implementation notes
type WhereNode = {
Base: NodeBaseInfo
Condition: string // Condition tensor
X: string // Tensor selected when true
Y: string // Tensor selected when false
Output: string // Selection result
Attributes: AttributeADT list
}
Check that dtype(Condition)=bool, broadcast(X,Y,Condition) is valid, and dtype(Output)=dtype(X)=dtype(Y).
5.12 Activation and Normalization Nodes
5.12.1 Softmax
Specification and opset changes
v11 coerces the input to 2-D and defaults to axis=1 (legacy semantics).
From v13 onward, there is no 2-D coercion. Normalization operates directly along axis, which defaults to -1, as in modern implementations. Types are restricted to floating point.
Mathematical formulation
Along axis (normalized to ), fix all other indices :
Implementations often use for numerical stability. It is mathematically equivalent to the equation above and is optional under the specification.
Typical use in GPT-2
Apply softmax to the attention score matrix along its last dimension, the sequence of keys for each query: axis=-1.
ADT correspondence and implementation notes
type SoftmaxNode = {
Base: NodeBaseInfo
Input: string // Input tensor
Output: string // Softmax output
Axis: int option // Axis of computation (attribute)
Attributes: AttributeADT list
}
Infer shape(Output)=shape(Input). For v13+ the default Axis is -1. Normalize it to [0,r-1].
To support older v11 graphs, handle the legacy 2-D coercion in the validation layer.
Three useful properties of Softmax
The inputs are arbitrary real scores, often called logits, . Imagine mixing flavors in a cup: Softmax converts the scores into proportions that add up to exactly 100%.
A high-scoring flavor comes through more strongly. Its advantage is not linear: exponentiation amplifies the differences, increasing the share of high scores at the expense of low ones.
Add the same constant to every score, as if lifting an entire landscape, and Softmax remains unchanged:
Implementations therefore often subtract the largest value:
This leaves the result unchanged while preventing from overflowing (numerical stability).
Introduce a temperature (also written ):
At (high temperature), the distribution flattens toward uniform. At (low temperature), the winner takes nearly all the probability, with the others close to zero. The limit gives the discrete argmax choice.
Common questions
Why probabilities? After normalization, every and the values sum to one. Each can be interpreted as the probability of selecting class or word .
Why mask positions with a large negative number first? To disable a key position in attention, add a large negative value, such as , to its logit. After Softmax its probability is nearly zero. This is the mask.
How are Softmax and Sigmoid related? In binary classification with , Softmax reduces to Sigmoid. Both convert log scores to probabilities.
A miniature worked example
Raw scores: . Subtract the maximum: . Exponentiate: . Normalize: . The first entry's share is amplified exponentially, but remains below 100%, leaving some room to explore the other choices.
Practical tips
Subtract the maximum first for numerical stability.
Adjust the temperature for a sharper or more balanced distribution.
In attention or classification, mask unavailable positions by adding a large negative number.
Only relative differences matter: shift invariance means that adding the same constant everywhere leaves the result unchanged.
Remember Softmax as exponential amplification, normalization to 100%, shift invariance, and adjustable temperature.
5.12.2 GELU
Semantics and equations (elementwise)
Exact form (default):
If approximate="tanh", use the fast approximation:
The approximate attribute accepts "none" (default) or "tanh". Input and output share a floating-point type (bf16/f16/f32/f64). This operator is available from opset 20.
Typical use in GPT-2
FFN (MLP) activation: Gemm → Add → Gelu → Gemm. Many exports use the tanh approximation for speed. (ONNX)
Consider restricting Approximate to a discriminated union:
type GeluApprox = | None | Tanh
This avoids arbitrary strings.
The shape is preserved. Require dtype(Y)=dtype(X) and a floating-point dtype.
5.12.3 LayerNormalization
Two-stage definition and equations
The normalized subspace runs from axis to the last dimension. Let normalized_axes = [axis, …, rank(X)-1]. The first stage standardizes:
The second stage is an affine transformation, broadcast to give the same output shape as X:
Optional outputs are Mean = and InvStdDev. Their shapes replace the normalized dimensions with , for example . Attributes. axis defaults to , epsilon to . stash_type (default 1) specifies the precision of the mean, inverse standard deviation, and first-stage computation. For example, stash_type=1 requires the first stage to compute in fp32. Type constraints: the inputs and Y are floating point (bf16/f16/f32/f64). Mean/InvStdDev allow {bf16, f32}. Scale and B are applied with unidirectional broadcasting. This operator is available from opset 17.
Typical use in GPT-2. axis=-1 normalizes along the last dimension, epsilon≈1e-5, and the final dimension of Scale/B matches the hidden dimension and broadcasts to X.
ADT correspondence and recommendations
type LayerNormalizationNode = {
Base: NodeBaseInfo
X: string // Input tensor
Scale: string // Scale parameter
B: string // Bias parameter
Y: string // Normalized output
Mean: string option // Mean output
InvStdDev: string option // Inverse standard deviation output
Axis: int option // Normalization axis (attribute)
Epsilon: float option // Small value to prevent division by zero (attribute)
Stash_type: int option // Intermediate-value type (attribute)
Attributes: AttributeADT list
}
Inputs. B is optional in ONNX. To match the specification exactly, B can be changed to string option.
Attribute defaults. Axis defaults to , Epsilon to , and Stash_type to 1 (compute the first stage in fp32 and return Mean/InvStdDev of type U under the type constraints).
Static checks
Scale and B must support unidirectional broadcasting to X.
The shape of Mean/InvStdDev replaces the normalized dimensions with .
5.13 Building the NodeADT Type by Composition in Place of Object Inheritance
Modern deep learning frameworks often create computation-graph nodes through object inheritance. This design makes extension straightforward but can also result in deep class hierarchies and unnecessary complexity. Here we use algebraic data types (ADTs) in place of traditional inheritance to give graph nodes a more concise and flexible representation.
In this implementation, NodeADT represents every kind of computation-graph node, including tensor operations, arithmetic operations, and shape transformations. Each node kind is an ADT variant. All variants share the common base information in NodeBaseInfo, providing a uniform structure.
// Union type representing all supported node types
type NodeADT =
| MatMul of MatMulNode
| Concat of ConcatNode
| Reshape of ReshapeNode
| Add of AddNode
| Sub of SubNode
| Mul of MulNode
| Div of DivNode
| Gemm of GemmNode
| Transpose of TransposeNode
| Slice of SliceNode
| Gather of GatherNode
| Shape of ShapeNode
| Unsqueeze of UnsqueezeNode
| Squeeze of SqueezeNode
| Cast of CastNode
| Constant of ConstantNode
| Range of RangeNode
| ReduceMean of ReduceMeanNode
| Pow of PowNode
| Sqrt of SqrtNode
| Split of SplitNode
| ConstantOfShape of ConstantOfShapeNode
| Where of WhereNode
| Softmax of SoftmaxNode
| Gelu of GeluNode
| LayerNormalization of LayerNormalizationNode
| Generic of {| // For operator types not explicitly defined
Base: NodeBaseInfo
OpType: string
Inputs: string list
Outputs: string list
Attributes: AttributeADT list
|}
With object inheritance, each computation becomes a subclass of Node, and inheritance provides polymorphism. With an ADT, distinct variants represent the different nodes. Each variant carries only its own data structure and operations and inherits no properties from other types. This reduces class complexity, improves expressiveness, and avoids a web of inheritance relationships that can be difficult to maintain.
This section used composition of ADTs to represent graph nodes directly and concisely. Avoiding the machinery of object inheritance makes node types easier and more flexible to extend. This follows the approach to Algebraic Code design discussed in §3.4, with its emphasis on structure and higher-order composition.
5.14 Concluding Remarks
Establishing the architecture. Starting with Attention Is All You Need, the Transformer replaced recurrence and convolution with self-attention and became the common backbone for modern LLMs. GPT-2 extended this architecture to large-scale autoregressive language modeling, establishing the path from pretraining to downstream generalization.
Implementation and naming. Libraries such as Hugging Face implement a layer as ln_1 → attn(c_attn/c_proj) → Add → ln_2 → mlp(c_fc/gelu/c_proj) → Add. These names correspond directly to those in an ONNX graph viewed in Netron.
Long contexts and positions. RoPE and ALiBi encode relative position with rotary phases and linear biases, respectively. Both are widely used for long contexts and extrapolation, and have inspired interpolation methods and other variants.
Systems acceleration. Through I/O-aware tiling, FlashAttention reorganizes data movement to reduce pressure on GPU memory bandwidth. The resulting improvements in training and inference efficiency make it an important component of modern LLM systems.
The method throughout the chapter is abstraction → alignment → lowering. Begin with a mathematical or operator-level abstraction, align it with the concrete GPT-2/ONNX graph, and then use a profile and backend kernels to lower and optimize it.
CHAPTER 6
Implementing Automatic Differentiation for Deep Neural Networks
This chapter introduces the established and widely used theory of automatic differentiation and implements it in Algebraic Code, primarily with variants.
Machine learning uses data to select and train models that perform well on unseen examples. We supply data and a learnable rule (the model), define a loss function that measures performance, and train the model to reduce that loss. Deep learning (Goodfellow et al., 2016) is a branch of machine learning that uses multilayer neural networks to learn successive levels of representation, reducing the need for hand-designed features. Optimization drives training. At each iteration, the model's performance on a small batch of data guides a parameter adjustment in a direction that reduces loss. Automatic differentiation (AD) provides the gradient used to find this descent direction. It decomposes a computation into primitive operations and applies the chain rule to obtain gradients automatically, accurately, and efficiently. Deep learning generally uses reverse mode (VJP) to obtain update signals for all parameters in one pass. AD supplies gradients, the optimizer uses them to update parameters, and deep learning trains a network through many such updates, all within the broader field of machine learning.
The literature distinguishes four broad approaches to computing derivatives in programs (Baydin et al., 2018):
Manually derive and code the derivatives.
Numerical differentiation using finite differences.
Symbolic differentiation using a computer algebra system (CAS).
Automatic or algorithmic differentiation (AD).
AD became the prevailing approach because it combines correctness with time efficiency. It computes gradients accurate to machine precision at the same order of complexity as the forward program, without explicitly constructing a Jacobian. In a deep learning framework, AD connects the forward computation to the optimizer's update.
Automatic differentiation, particularly reverse-mode VJP, is central to a deep learning framework's ability to train models. It automatically and accurately converts a network's forward computation into gradients that optimizers such as SGD and Adam use to update large numbers of parameters. Training networks at modern scales would be almost impractical without AD. Frameworks also rely on efficient tensor operators and kernels, graph compilation and scheduling, memory management and numerical stability, distributed parallelism and device management, and data pipelines (Elliott, 2018; Pearlmutter & Siskind, 2008).
Table 6-1. Comparison of differentiation methods
Method
Typical difficulty
Suitable applications
Manual differentiation
High maintenance cost: changing the model means changing its derivative.
Small, fixed formulas or heavily hand-tuned implementations
Finite differences (forward or central)
Rounding error and very slow computation in high dimensions
Gradient checking and rough estimates for black-box functions
Symbolic differentiation
Difficult control flow and data dependencies; large generated programs
Algebraic derivation and closed-form analysis
Automatic differentiation (AD)
Requires runtime or compile-time transformations and a library of rules
The default for modern deep learning and differentiable programming
Implementing AD in Algebraic Code establishes a one-to-one correspondence between program structure and mathematical formulas. We concentrate on the principles of AD and practical computational techniques. The chapter includes many formulas for use in implementations, without pursuing every derivation, formal proof, or purely mathematical question.
6.1 Terminology: Analytical and Geometric Perspectives
Early AD research, including work by Griewank and Walther (Griewank et al., 2012; Griewank & Walther, 2008), drew on the language of numerical differentiation and differential geometry. Geometric terminology has persisted in the literature: pushforward and pullback are a natural pair of names for the JVP and VJP. Deep learning increasingly deals with non-Euclidean structures in graph neural networks, manifold embeddings, and group convolutions. Two theoretical languages are therefore common when implementing AD for deep networks. They describe the same underlying operations at different levels of abstraction.
6.1.1 The Perspective of Mathematical Analysis (Default)
Object. For , the Jacobian at has the matrix representation
,
Row is the gradient of the scalar function , expressed as a row vector.
JVP(Jacobian–vector product): given an input direction ,
This is the directional derivative, or pushforward.
VJP(vector–Jacobian product): given an upstream sensitivity at the output,
This is the pullback, propagated in the reverse direction. Superscript denotes transposition.
Duality identity
.
Expanded form:
Chain rule. For the composition ,
,
.
Engineering rationale. This notation matches mainstream frameworks such as PyTorch and TensorFlow. For a scalar loss, , a single chain of VJPs yields all parameter gradients at the same time complexity as a forward pass.
6.1.2 The Differential-Geometric Perspective: Manifolds
Object. Consider a smooth map . Given a tangent vector in the tangent space at , the differential
gives
(the JVP).
A covector in the cotangent space is carried by the adjoint map
back to
(the VJP).
Applications. This language gives a unified account of non-Euclidean structures such as SO(3), Riemannian optimization, and geometric deep learning. “Pushforward” and “pullback” make the duality of forward and reverse operations explicit.
In Euclidean space, Tₓℝ² can be identified with ℝ², and a tangent vector is a two-dimensional direction or velocity. At the same point,
.
Figure 6-1. A point in , its tangent space, and a tangent vector.
Figure 6-2. Geometric interpretation of the JVP. Given a point x and an input direction v, push the direction forward to obtain the instantaneous direction of change at the output, .
Table 6-2. Terminology and notation used in this book
Concept
Analytical perspective (default notation)
Geometric perspective
Tangent vector
(also written )
Covector / upstream gradient
JVP
VJP
Duality identity
This chapter primarily uses notation, with a dot denoting a tangent vector and a bar denoting a covector. Batch examples are stacked in columns by default. We use manifold terminology when the geometric meaning matters, for instance for pushforwards, pullbacks, or manifold parameterizations. This keeps the notation close to common engineering practice and permits extension to more general settings.
6.2 Machine Learning Methods
In supervised learning and most deep learning, we treat model parameters as variables and solve for them by optimizing an objective (risk or loss). AD supplies the gradients via VJP/JVP, and an optimizer such as SGD or Adam updates the variables. Treating parameters as variables and minimizing loss is the most common operational principle in practical machine learning, particularly deep learning. The broader field also includes probabilistic inference, sequential decision-making, and nonparametric methods that go beyond parameter optimization.
6.2.1 Empirical Risk Minimization (ERM): The Baseline in Deep Learning
Model the problem as . Given a training set , define the following objective, optionally with regularization:
A first-order method updates the parameters as follows:
is computed efficiently with a VJP or backpropagation.
6.2.2 The Bayesian Perspective: Learning as Inference Beyond Optimization
Treat the parameters as random variables with prior and likelihood . Learning becomes posterior inference:
Seeking only a point estimate (MAP) brings us back to optimization:
Full Bayesian inference involves integration or sampling. Variational inference introduces a distribution and optimizes to approximate the posterior by optimizing the evidence lower bound (ELBO).
Learn a policy that maximizes the expected return:
This remains an optimization problem, now with an expectation over sequential decisions as the objective.
6.2.4 Nonparametric Methods and Other Algorithms
In nonparametric methods such as k-nearest neighbors, kernel methods, and Gaussian processes, training either involves little parameter optimization or performs optimization in a function space or over a kernel matrix.
Decision trees and random forests commonly use greedy splits to minimize impurity, a form of optimization that does not require gradients.
Structure learning, neural architecture search, and hyperparameter tuning optimize the learning system itself, as in AutoML and meta-learning.
6.2.5 Connections to VJPs and JVPs
Most deep learning fits the paradigm of optimizingover , where the gradient provides the central information:
The VJP obtains all parameter gradients in a single reverse pass.
JVPs are common in second-order and sensitivity computations, including directional derivatives, Hessian–vector products, influence functions, and Jacobian regularization:
6.3 Introducing Batches
6.3.1 Minibatches
Let the batch size be and the batch data be . The forward pass yields and the batch loss
Differentiating by backpropagation is equivalent to averaging the gradients of the individual examples:
6.3.2 Vectorization and Shapes
Use the leading dimension as the batch dimension (or use another agreed axis), and manage it with broadcasting and reductions:
For BiasAdd, compute from by applying over the batch axis and the other broadcast axes.
Primitives such as MatMul can use batched matrix multiplication along the batch axis or be mapped across examples using vmap.
Per-example gradients. For DP-SGD or importance sampling, defer averaging over the batch. Accumulate per example, then aggregate according to the chosen policy.
Sequence batches (RNN/LSTM). A common shape is .
BPTT unrolls reverse propagation along the time dimension and accumulates gradients through time. TBPTT truncates the propagation in windows to control memory use and exploding gradients.
The batch loss is .
6.4 Computational Techniques for JVPs and VJPs
6.4.1 Scalar Outputs () and Gradients
If , or more generally with , then
The entire gradient of a scalar loss can therefore be obtained in a single reverse chain of VJPs. This accounts for the efficiency of reverse mode.
6.4.2 Functions of Several Arguments: JVPs and VJPs for Selected Arguments
If takes several arguments, as in , write the Jacobian block as
JVP with respect to
VJP with respect to all arguments (returning a tuple of covectors in one pass)
In a typical training computation, view as . Then . Thus one reverse pass produces both activation gradients for continued backpropagation and parameter gradients for the update.
6.4.3 Batches and Seed Matrices (Batched or Multiple Seeds)
Column-wise batching. Write and . Let .
VJP with respect to inputs (parallel over example columns)
VJP with respect to the shared parameters (summed across examples)
Multiple-direction JVPs and multiple-upstream VJPs. Stack several (or ) as the columns of (or ). One computation gives (or ).
6.4.4 Linear Layers: Dot Products and Outer Products in Notation
For an affine map (or for a column-wise batch):
Main observation. The pullback to inputs or intermediate values uses matrix multiplication (dot-product contraction). The pullback to parameters uses outer products summed over the batch. This is a concrete example of the block VJP rule above.
6.4.5 Higher-Order Derivatives
Hessian–vector(Pearlmutter trick):
This is also commonly written as a nested JVP/VJP, in reverse-over-forward or forward-over-reverse form.
Table 6-3. JVP and VJP quick reference
Case
Input/output
Seed
Result
Basic JVP
Basic VJP
As above
VJP with multiple arguments
Batched VJP (inputs)
Batched VJP (parameters)
Shared
Multiple-direction JVP
—
Summary
A dot () denotes a tangent vector, and a bar () denotes a covector.
A JVP gives , and a VJP gives .
Use the chain rule for composition.
The VJP of a function of several arguments returns a tuple of covectors in one pass.
Within a batch, propagate independently to input columns and sum across examples for shared parameters.
For higher-order information such as Hessian–vector products, nest JVPs and VJPs.
6.5 AD in Learning: Forward Pass → Reverse Pass (AD/VJP) → Optimizer Update
Optimization objective. Minimize empirical risk, optionally with regularization:
One training iteration on the current minibatchhas three steps:
Forward pass. Compute the predictions and minibatch loss .
Reverse pass (AD/VJP). Automatic differentiation gives the parameter gradient
This step is independent of the optimizer. AD's task is to compute gradients accurately and efficiently.
Optimizer update. Use and the optimizer's internal state to advance to the next step.
6.5.1 Typical First-Order Optimizers (Depending Only on , Independently of AD)
SGD
SGD with momentum (Polyak)
Adam
6.5.2 An ADT Perspective: The Optimizer as a Pure Update Function
Define the optimizer state, retaining only the quantities it needs:
A common update interface, expressed as a composable pure function:
For example,
Design principle. AD produces . The optimizer uses and its own state to update the parameters. Expressing the optimizer as an ADT and a pure function keeps the definition of learning algebraic and composable, so optimization strategies can be exchanged or combined independently of AD.
6.6 AD for a Multilayer Perceptron
We derive the JVP and VJP for a multilayer perceptron (MLP) as a chain of equalities. By default, stack the batch in columns: . For layer ():
A bar denotes a covector (upstream gradient), and a dot a tangent vector (directional derivative). Use the Frobenius inner product:
That is, takeand sum all its elements. More explicitly:
Vectors: , the ordinary dot product.
Matrices :
A general tensor of order and shape :
Relation to batches and broadcasting. The tensors must have the same shape, possibly after broadcasting. For example, in , the shapes are and . Broadcast along the batch axis to , then sum over all elements. Equivalently,
This yields . Below, denotes differentiation (the prime). The expression is the first derivative of the activation of layer , evaluated at . It acts elementwise and has the same shape as . Thus
This multiplies the upstream gradient elementwise by the derivative of the activation. Common elementwise examples are:
ReLU:
Sigmoid:
Tanh:
6.6.1 VJP / Reverse Mode: All Gradients in a Single Backward Chain
Let the loss be , with having the same shape as . Starting at the final layer, expand the inner products of differentials in a chain of equalities:
This gives three VJP results for the layer's parameters and activations:
For any intermediate layer , the same chain of equalities gives
The recurrence is therefore
Summing over all layers gives
where .
This shows that , , and . A single reverse chain of VJPs gives every gradient.
6.6.2 JVP / Forward Mode: Pushing Directions to the Output
Given directional seeds (tangent vectors)
Proceed layer by layer in the forward direction, moving the dotted quantities to the right-hand side of the equalities:
That is,
This pushes directions in the inputs and parameters to a direction at the output in a single pass.
6.6.3 Duality of the JVP and VJP as a Chain of Equalities
The chain of equalities relates the forward directional derivative exactly to the reverse gradient. The left-hand side takes a JVP and then an inner product. The right-hand side takes a VJP and then an inner product. Both paths give the same number.
In summary:
The reverse pass (VJP) uses a chain of equalities involving to decompose layer by layer into outer products (parameter gradients) and dot products or matrix products (activation pullbacks).
The forward pass (JVP) pushes the dotted quantities forward to obtain the output direction.
The last chain of equalities gives the exact correspondence between the two.
6.7 How AD Improves Computational Efficiency
6.7.1 The Complexity of AD
Time complexity: classical results and practical observations
Write for the cost of one function evaluation.
Forward mode. Each input direction costs . The full gradient costs .
Reverse mode. Each output direction costs (the implementation-dependent constant is typically in the range ). The full gradient of a scalar loss () needs one pass, costing .
The Baur–Strassen principle: for a straight-line program, computing the gradient of a scalar output costs at most a constant factor more than .
Conclusion. In deep learning, training almost always has , a scalar loss. VJP/reverse mode therefore has the time advantage.
6.7.2 Why AD Is Fast: Multiplying by the Jacobian Without Constructing It
Explicitly constructing at a cost on the order of function calls would almost always be prohibitive. AD directly computes
without materializing . This is the matrix-free approach: treat the operator as a black box and ask only for products with vectors. Many second- or higher-order algorithms, including conjugate gradients and Newton approximations, require only a Hessian–vector product:
Alternatively, use mixed mode: (Pearlmutter's trick). This makes second-order information available at the cost of one or two first-order passes.
6.7.3 Acceleration Techniques Used in Mainstream Frameworks
Mode selection and mixing
For scalar outputs, choose VJP/reverse mode. For very low input dimension or only a few directional derivatives, choose JVP/forward mode.
Combine jacrev/jacfwd with forward-over-reverse or reverse-over-forward. Choose the cheaper path based on versus .
Batched seeds and vectorization (vmap/pmap)
Stack several seeds as a matrix, using or . Compute or in one operation to exploit BLAS or GPU parallelism. This can be much faster than repeated calls in a for loop.
Operator fusion and JIT/graph compilation
Inline elementwise VJPs/JVPs with neighboring operators and fuse them into a small number of kernels to reduce memory traffic and scheduling overhead.
Constant folding, common subexpression elimination, memory reuse, and layout optimization reduce itself. Gradient computation benefits proportionally.
Reverse mode needs intermediate values. Save a subset and recompute the rest during the backward pass according to a schedule.
A typical strategy reduces peak device memory from to while increasing execution time by only a constant factor.
Structured VJP/JVP rules
The backward pass for convolution combines correlation, kernel reversal, and the corresponding stride and padding operations.
For triangular or general linear solves, compute the VJP with a transposed solve in place of an explicit inverse.
Combine softmax and cross-entropy (CE) gradients as to avoid numerical instability and unnecessary operators. Specialized rules turn expensive general Jacobian operations into inexpensive standard linear algebra.
Implicit differentiation
For an inner optimization or a fixed-point equation , use
and replace explicit backpropagation through a long iteration with a linear solve or CG using Hessian–vector products. This requires less time and memory than unrolling T steps and differentiating backward through them.
Exploiting sparse and block structure
The VJP/JVP of a sparse linear layer or graph operator multiplies vectors using only the nonzero entries.
For a block Jacobian, multiply only the active blocks and avoid converting it to a dense matrix.
Numerical stability and mixed precision
Techniques including logsumexp, stable normalization or scaling factors, and loss scaling for bf16/fp16 can reduce the number of iterations or retries and thereby shorten total execution time.
These techniques do two things: avoid explicitly constructing and reduce the cost or increase the parallelism of each product with a vector.
Table 6-4. Efficiency of different differentiation methods
Method
Correctness
Complexity (computing )
Manual differentiation
Depends on the programmer; error-prone
Can match the complexity of AD
Finite differences (forward or central)
Approximate, with a step-size trade-off
/
Symbolic differentiation
Exact formula
Expression-dependent, often with expression swell
Automatic differentiation (AD)
Gradients accurate to machine precision
Scalar output: . General case: first-order passes.
In the usual deep learning setting of many parameters and a scalar loss, AD based on reverse-mode VJPs has better time complexity than finite differences. It avoids the maintenance problems of symbolic and hand-coded differentiation while delivering gradients accurate to machine precision.
6.7.4 The Efficiency of Computing Intermediate and Parameter VJPs Together
Consider two fully connected layers with the batch in columns:
Given :
Pullback to intermediate values
Parameter gradients
The same VJP pass yields both activation gradients for continued backpropagation and parameter gradients for the update. Both use matrix–vector products or outer products. No Jacobian is constructed, and the time complexity matches that of the forward pass. This is the source of backpropagation's efficiency.
6.7.5 Efficiency at Second and Higher Orders
Hessian–vector product (Newton methods, conjugate gradients, and influence functions):
One or two first-order passes suffice. This can be orders of magnitude faster than constructing the Hessian explicitly ().
Jacobian trace and divergence estimation. The Hutchinson estimate can be evaluated using one JVP per sample. It is often used in regularization and flow models.
6.7.6 Conclusion
AD's time efficiency comes from using JVP/VJP products with vectors in place of explicit Jacobians or black-box differences, choosing the mode according to output and input dimensions, and using fusion, vectorization, recomputation, structured rules, and implicit differentiation to bring each product close to the cost of the underlying linear algebra. In deep learning with a scalar loss, one reverse chain of VJPs gives all parameter gradients at the same order of cost as a forward pass. This makes modern training scalable.
6.8 Rules for Reverse-Mode Backpropagation: The ReverseGraph Transformation
The VJP is the mathematical basis of backpropagation in neural networks. We begin with a scalar loss and compute gradients such as . Let . If we know the loss gradient with respect to the output, , the chain rule gives its gradient with respect to the input as . Thus a VJP maps the output gradient back to the inputs, the essential operation of backpropagation. An implementation applies a VJP at each layer and propagates the gradient backward without constructing the Jacobian. A typical network's final training output, its loss, is scalar. One reverse chain of VJPs therefore computes all parameter gradients at the same order of complexity as the forward calculation. Forward-mode JVPs generally need repeated computations to obtain every parameter gradient, equivalent to computing one Jacobian column at a time. That cost becomes very large in high parameter dimensions. A single scalar output, such as a network loss, consequently favors reverse mode.
This section expresses backpropagation as programmable rules for ReverseGraph. The aim is to obtain gradients for parameters and intermediate values in one backward pass, using local VJP rules and structural composition laws. The central idea is:
Each node denotes a value and a pullback, a linear operator that propagates sensitivities backward. Primitives provide local VJPs. Structural nodes for composition, parallelism, and packing provide the composition laws.
6.8.1 ReverseGraph Semantics and Interface
The WithPB pair (value and pullback)
pb is a linear operator. It accepts the upstream and distributes contributions into the gradient accumulators for the node's inputs and parameters. Multiple uses of the same parameter must accumulate their contributions.
The backward program composes the nodes' pullbacks in reverse order.
The Reverse transformation: from forward nodes to nodes with pullbacks. For any forward node n, write
Here v is the forward value and pb the node's pullback. Apply the outermost pb to the output covector to obtain the gradients of the entire graph.
6.8.2 Composition Laws for Structural Nodes, Independent of the Primitives
Chain : evaluate in order. The output is . On receiving , the pullback performs
In implementation, each step passes its covector to the previous node's pb, composing in reverse order.
Parallel / Bundle : the forward pass returns the tuple . The pullback passes the components of to their respective pb_i.
Select i / In i / Sole: select or reference a component of a packed value. On the backward pass, put into the corresponding component and zero the others.
Param p / Tensor t / ShapeParam s:
The pb for Param p adds the incoming to the global accumulator: Grad[p] += W̄.
A constant or input Tensor accumulates a gradient only if it participates in differentiation.
ShapeParam is nondifferentiable and is ignored in the backward pass.
SubGraph: recursively apply in the child environment. Its pb passes the outer to the subgraph's pb. Map parameter and tensor IDs back to the outer environment and accumulate the gradients there.
Consequently, once the primitive VJPs are defined, the composition laws suffice to run the entire ReverseGraph.
6.8.3 VJP Rules for Common Primitives (Obvious Shape Details Omitted)
Write . All elementwise rules include unbroadcast where needed.
Elementwise and linear operations
Addition: gives and .
Hadamard: , .
Affine transformation: (or for a column-wise batch)
Matrix multiplication: gives and (align the batch dimensions in the batched version).
Activations (elementwise)
Sigmoid: .
Tanh: .
ReLU:.
Linear:.
Shape operations and aggregation
Sum (along axes): gives .
Concat (along an axis): gives .
Stack: use unstack_axis in the backward pass.
Reshape / Flatten:.
Transpose/Permute:.
Softmax and cross-entropy (batch mean)
If and , the combined formula is . It is numerically stable and straightforward to implement as a primitive pullback.
6.8.4 Rules for the Reverse Transformation (Illustrative Semantics)
Const :.
Param :.
Unary : let and .
Binary :, , .
Chain / Parallel / Bundle / Select / In: build pb using the composition laws in §6.8.2.
SubGraph: recursively apply in the child environment. Its pb delegates to the subgraph pb and accumulates gradients back in the outer environment through ID mappings.
These rules are the interpreter semantics of ReverseGraph. To execute them, (1) run the forward pass once to obtain each node's value and pullback closure, then (2) invoke the outermost pb with the upstream covector for the loss. Gradients accumulate automatically throughout the graph.
6.8.5 Batches
We now incorporate batch-aware rules into the ReverseGraph transformation from the preceding discussion. Retain the value-and-pullback structure of ReverseGraph and make axis information and reduction and broadcasting explicit in the VJP rules.
A minimal extension for batch axes
Named axes. Label the dimensions of each tensor, for example and .
Two basic operators used at the end of VJP rules
sums over the set of axes (a reduction).
expands or replicates to match the axes of . In the implementation these are the existing unbroadcast/broadcast_to_shape operations, with the affected axes made explicit.
For a shared parameter broadcast across a batch, first use the local formula to compute of the same shape as the output. Then reduce over the broadcast axes using . This one rule covers BiasAdd, affine biases, and weights broadcast across a batch.
Batch-aware VJP rules for primitives, with explicit axes
The rules below show only the mathematical core. In implementation, replace shape tests with axis tests.
Addition / BiasAdd
For , suppose is broadcast along axes (for example, ).
Sum (reduction over axes)
Concat / Stack (concatenating or stacking along an axis)
Affine layer (column-wise batch)
If the loss is a batch mean, the upstream already includes the factor . No further division is needed here.
MatMul as batched matrix multiplication with leading axes S
Write . Then
This covers three common cases:
Same batch. Both carry . Compute separately for each batch element.
Onlyis batched, with broadcast across the batch: and .
Onlyis batched: proceed symmetrically.
Elementwise activations (ReLU/Sigmoid/Tanh/…)
As in the unbatched case, . The implementation need only ensure correct axis alignment and broadcasting.
Softmax and cross-entropy (batch mean)
If and , then
This already includes the batch-averaging factor .
How ReverseGraph incorporates the rules
Reuse the preceding framework and introduce axis parameters only in the VJPs of primitive nodes:
Illustrative node signature: . In the implementation, use to decide whether an additional is needed.
The Reverse composition laws for Chain, Parallel, Bundle, and the other structural nodes stay the same. When pb sends local gradients to the preceding node, it calls the appropriate reduction or broadcasting routine.
A worked example: two-layer MLP with examples in columns
We obtain
The axis-aware rules give exactly this result: for every parameter broadcast across the batch, including biases and broadcast weights, reduce over . Everything else follows the unbatched case.
Implementation notes
Axis metadata. Attach axes to Value, or keep a dictionary from tensors to axis labels in DefContext.
Common library functions. Provide reduce_sum_axes(T,S), broadcast_to_axes(G,axesX), and split_axis/stack_axis.
Rules specify which axes to use. Pass S (for example, {batch}) as a parameter and avoid hard-coding shapes.
Consistent means and sums. Specify whether the loss is averaged over the batch. If it is, apply upstream, as in the combined CE formula. Downstream rules should not scale it again.
Generalization. Extend to additional axes such as time for BPTT/TBPTT. For parameters broadcast across time, take an additional reduction over {time}.
In brief:keep ReverseGraph's value-and-pullback structure and give each primitive VJP rule explicit axis parameters. The gradient of any parameter broadcast over those axes is summed over them. The same rules cover BiasAdd, Sum, Concat, and MatMul (including batched MatMul) and naturally handle several axes, such as batch and time.
6.8.6 Design Considerations
Linearity and accumulation. pb must be linear. Add gradient contributions from every path to the same variable at a join in the DAG.
Consistent broadcasting. Pair elementwise rules with unbroadcast/broadcast_to_shape. Distinguish batch and channel axes explicitly.
Numerical stability. Use a fused pullback for softmax and cross-entropy, and specify normalization and summation axes explicitly.
Extensibility. A new primitive needs one VJP rule. The structural and composition layers need no changes.
Subgraphs and shared parameters. ParamMap must send all gradient contributions for a given parameter to the same slot.
Optional memory strategy. With checkpointing, pb can recompute forward values internally as needed.
Apply to transform the forward graph into a ReverseGraph of WithPB pairs (value and pullback). Primitives define VJPs, and structural nodes define composition laws. A single call to pb accumulates gradients across the graph in reverse order. These are the rules of backpropagation.
6.9 Concluding Remarks
AD is the “gradient bus” between the training engine and the optimizer. The forward pass maps data to a loss. Reverse-mode AD (VJP) generates gradients for all parameters in one pass and hands them to an optimizer such as SGD or Adam. This is the basis of scalable training in modern deep learning frameworks. See the JMLR survey by Baydin and colleagues.
Two perspectives and two basic operations. Forward mode computes a JVP (), and reverse mode computes a VJP (). The appropriate mode depends on the relative dimensions of the input and target. The common machine learning case of many parameters and a scalar loss favors VJPs.
Semantics and composability. Making reverse mode a first-class language feature allows AD to work naturally with higher-order functions, closures, and nested differentiation. Pearlmutter and Siskind give the semantics and an implementation in a functional setting in “Lambda the Ultimate Backpropagator.”
A simple underlying idea unifies variants of AD. Elliott treats AD as a general algorithm that can be specialized, using program calculation and category theory. This helps keep the core of an Algebraic Code implementation small, complete, and verifiable.
Theory and numerical robustness. The classic Evaluating Derivatives systematically covers the principles, complexity, and stability of AD, including higher derivatives, branches, and fixed points. It is a standard reference linking implementation with numerical analysis.
Connection to machine learning methodology. The forward pass → reverse pass (AD/VJP) → optimizer update training loop fits the empirical-risk-minimization perspective. For a textbook treatment of the relationship between backpropagation and AD, see Deep Learning, §6.5.
In short, AD turns a differentiable program into a trainable model. An algebraic implementation connects naturally to the abstract syntax or computation graph, to type and shape checking, and to backend lowering (Chapters 4–5).
CHAPTER 7
Approximating the Logical Meaning of Natural Language with ADT Variants
Turning natural language into executable meaning is a critical step between language, knowledge, and inference. This chapter develops a controlled engineering approach. Using ADT variants (sums of products) as a skeleton, we recast sentences and fragments as well-typed tokens. The representation preserves distinctions that matter: predicates and arguments, modification, value constraints, events, and participants. It also gives us something we can compose, check, and run. The aim is a stable intermediate representation for structured retrieval, rule checking, and verifiable inference, without requiring a complete linguistic semantics.
Background and motivation. Since Montague, formal semantics has emphasized compositionality: the meaning of an expression depends on the meanings of its parts and how syntax combines them. A typed lambda calculus commonly implements this syntax–semantics homomorphism. The tradition established that natural language can be mapped to logical terms and typed objects. It also explains how a small number of combinators and types can build up complex expressions. In parallel, frameworks such as combinatory categorial grammar (CCG) tightly couple syntax and semantics in a computationally tractable way. They provide working examples of how to derive semantic constructions from syntax.
Semantic representations and their trade-offs. Engineering-oriented semantic resources often use graph representations. Abstract Meaning Representation (AMR), for example, represents a sentence as a directed, labeled graph that highlights semantic roles and event structure. Discourse representation theory (DRT) addresses cross-sentence phenomena such as anaphora and tense. It constructs representations incrementally to handle reference and scope. Both approaches offer expressive detail, but annotation and parsing can be costly at scale, and the resulting representations may have little direct connection to downstream executors. Here we place the information a program most needs to compute in ADT variants, then add optional fields and constraints as needed. This balances coverage, complexity, and executability.
From semantic parsing to executable approximations. Semantic parsing maps text directly to logical forms or programs. Surveys trace rule-based, statistical, and neural methods. Neural sequence-to-tree and sequence-to-program approaches, such as the work of Dong and Lapata, show that systems can learn task-specific executable semantics. They still need well-defined target representations and constraints for control and transfer. We choose strongly typed ADTs and tokens as the target. Structured output and function calling constrain LLM generation to that schema, reducing ambiguity and cleanup afterward.
What will we do?
Establish minimal principles for mapping natural language to a token ADT. Prioritize predicates and arguments, modification and scope, events and participants, and common forms of quantification and negation. Preserve ambiguity explicitly where a reading is unresolved or still needs evidence.
Develop a reproducible treatment of the Jones Problem. Separate the passage into linguistic constructions, align them with ADT variants, and test the mapping with executable checks on types, constraints, and sample inferences. Compare the approach with PTQ, CCG, DRT, and AMR in terms of coverage, precision, and executability.
Pass the token representation to retrieval, constraint-checking, and inference programs. Connect representations to evidence and conclusions, and use evidence carried with a result and explicit proof objects to assess quality.
What will you take away?
An implementable, verifiable route from approximate semantics to an executable representation, with a clear distinction between information encoded in an ADT and information retained as evidence or left to establish.
A working intuition for compositionality and types in models of text meaning: why a few building blocks can cover many constructions.
A basis for comparing AMR, DRT, CCG, neural semantic parsing, and structured output, including their strengths and engineering trade-offs.
Within the book, Chapter 7 narrows the language-to-token step to something reliable. ADT variants carry the essential semantic distinctions, and types and constraints let us compose and execute them. A text becomes input we can compute over, inspect, and trace. Chapter 8 draws these ideas together as engineering principles.
7.1 An Engineering Approximation to Compositional Semantics: From Montague to ADTs and LLMs
Compositionality holds that the meaning of a complex expression depends on the meanings of its parts and the way they combine. Montague semantics made this idea systematic. A typed lambda calculus supplies the semantic machinery, and a correspondence between syntax and semantics maps phrase structure step by step to a composed semantic expression. Quantification, reference, and intensional terms, for example, receive interpretations by typed function application. This work set the course for modern formal semantics. For derivations from lexical types to sentence meanings and for typical operators, see the Stanford Encyclopedia of Philosophy entry and the textbook by Heim and Kratzer.
Formalizing natural language in full at this level and implementing the result is expensive. It requires fine-grained lexical types, inventories of semantic terms, and derivation rules. Ambiguity, scope, indexicals, and adverbial expressions all need attention. Products often use an engineering approximation that preserves enough compositionality for the job. We can use an algebraic data type to encode sentence patterns as constructors such as If, And, and Will, then use pattern matching and small rewrite or propagation rules for inference. Constructors determine what may combine. A match branch specifies what can be assembled or inferred when that shape appears. F# directly supports discriminated unions (ADTs) and pattern matching, making an interpretation of semantics as data shape easy to read and maintain.
The approach follows Montague in principle: meanings of parts plus rules of composition yield a meaning for the whole. In implementation, it replaces demanding higher-order logical inference with structured data and terminating local reductions. For example, we encode “If P and Q, then R will happen” as Force(If(And(P,Q)), Will R). Constructors and matches execute the composition without a general theorem prover. We give up formal completeness and open-domain coverage in exchange for readability, ease of change, and predictable runtime behavior.
LLMs have brought new questions to compositional semantics. Researchers continue to test compositional generalization in large models, including systematic generation and transfer in morphology and syntax. Even strong instruction-tuned models can be inconsistent on some challenges. This motivates external structural constraints and data that expose parts, relationships, and ways of combining them (Ismayilzada et al., 2024). Meanwhile, retrieval-augmented generation (RAG) (Lewis et al., 2020) introduces verifiable external knowledge into generation. It gives the LLM a kind of nonparametric memory, improving factual accuracy and traceability. It fits naturally with the idea of keeping composable semantic resources outside the model and invoking them during inference.
Work on knowledge graphs (KGs) and LLMs and on neurosymbolic methods couples structured knowledge (graphs, ontologies, and rules) to a model’s linguistic and statistical abilities in both directions. A KG can constrain or augment factual and logical reasoning, while an LLM can help construct and align a KG. Research distinguishes KG-enhanced LLMs, LLM-enhanced KGs, and joint reasoning frameworks. These illustrate the convergence of semantics and statistics (Pan et al., 2024). Surveys of neurosymbolic AI likewise identify the combination of interpretable symbolic rules with neural learning and generalization as a route toward controllable, verifiable intelligence (Hitzler & Sarker, 2021).
The position of this chapter is pragmatic. We use ADTs, pattern matching, and a small propagation kernel as an engineering approximation to compositional semantics. The path from natural language through a composable semantic structure to intuitive inference becomes runnable code. If stronger proofs or greater scale are needed, the same structure can be compiled to a stricter logic such as Horn clauses or Datalog, or connected to external knowledge through RAG or a KG. Montague offers a model of how meanings compose, ADTs offer a way to encode them, and LLMs, KGs, and RAG help extend the method to complex settings.
7.2 The Jones Problem: Modeling Meaning and Running Inference with an ADT
7.2.1 The Problem and Its Source
The classic statement of the Jones Problem comes from Logic for Applications (Nerode & Shore, 1997). The exercise asks the reader to convert a passage to Prolog and use resolution to prove that the directors will declare a dividend. The authors’ 2023 errata correct the sentence about Patterson in the second paragraph: if Patterson comes, he will bring Robinson to his senses, and he will come only if Jones is ill.
Here is a slightly modified version of the Jones Problem:
If you are told that Jones has fallen deathly ill and Smith has gone off to his bedside, you could determine if the directors will declare a dividend. If Jones is ill or Smith is away, then the directors will meet and declare a dividend if Robinson comes to his senses and takes matters into his own hands. If Patterson comes, he will force Robinson back to his senses but, of course, he will come only if Jones is ill. On the other hand, if Townsend, who is inseparable from Smith, stays away, Robinson will have to take matters into his own hands. Show that the directors will declare a dividend.
In the Chinese edition the passage is restated as follows, rendered here in English:
You are told that Jones is seriously ill and that Smith has gone to his bedside to look after him. Can you determine whether the directors will declare a dividend? If Jones is ill or Smith is away, the directors will meet. They will declare a dividend if Robinson comes to his senses and takes matters into his own hands. If Patterson comes, he will bring Robinson to his senses; of course, he will come only if Jones is ill. On the other hand, if Townsend, who is inseparable from Smith, fails to appear, Robinson will have to take matters into his own hands. Prove that the directors will eventually declare a dividend.
7.2.2 Why Can We Reason Before Building a Full Formal Logic?
Mapping natural language precisely to first-order logic or an ontology has occupied researchers for decades, as the tradition of Montague semantics illustrates. Going directly from full formalization to inference sets a high entry threshold and entails considerable implementation work on lexical items, quantifiers, scope, ambiguity, and reference. We can instead start from engineering needs and semantic intuitions: write the semantic structures directly into ADT constructors and execute inference by matching patterns and applying simple propagation or rewrite rules. This follows the tradition of defining program meaning through rewrite relations or operational semantics.
The traditional approach uses Horn clauses and SLD resolution, the inference mechanism underlying Prolog. It has a solid foundation for completeness, but converting natural language to Horn clauses is demanding, and implementation and tuning can be costly.
The approach used here turns expressions such as “if … then …,” “will,” and “and” directly into ADT constructors such as If, Will, and And(…, …). Trigger–consequence relationships become entries in a rule table. A worklist and recursive matching propagate conclusions. The theoretical background includes term rewriting, operational semantics, and bottom-up fixed-point inference, as in Datalog closure. The implementation requires only a small kernel.
7.2.3 An ADT Gives “Meaning as Data Structure” a Type Boundary
A minimal ADT:
type fact = Fact(id*string) | If of fact | Will of fact | And of fact*fact
type force = Force of fact * fact // When the fact on the left holds, trigger the Will or fact on the right.
Why is this minimal construction intuitive?
The constructors express the semantics. If denotes a condition, Will an anticipated event or consequence, and And(…, …) a conjunction. They are semantic names chosen for the reader. Someone reading the AST can recognize the shape of the original sentence.
Pattern matching dispatches the rules. Each constructor has a match branch whose body says what to do with that shape. The compiler’s exhaustiveness check turns the requirement to cover every semantic case into a compile-time issue the programmer must address.
Small-step semantics provides an executable interpretation. Read each Force(If α, Will β) as a rewrite or propagation rule: when α is satisfied or simplifies to a satisfied condition, add Will β to the results. For And(a,b), check recursively that both a and b can hold. This is a programming realization of structural operational semantics (SOS) and term rewriting, restricted to the part that is simple enough to read and run.
Implementation note: discriminated unions and pattern matching in F#, OCaml, and Haskell suit this style of programming. The languages and their compilers support checks for exhaustiveness and unreachable cases.
7.2.4 Translating the Jones Problem into an ADT: From the Chinese Wording to Constructors
A condensed paraphrase:
If Jones is ill or Smith is away, the directors will meet. If Robinson comes to his senses and takes matters into his own hands, the directors will declare a dividend.
If Patterson comes, he will bring Robinson to his senses. Patterson will come only if Jones is ill.
If Townsend, who is inseparable from Smith, is absent, Robinson will have to take matters into his own hands. We know that Jones is gravely ill and Smith has gone to look after him. pi.math.cornell.edu
Facts and names for the ADT, showing the essential structure:
Atomic facts: Jones_ill, Smith_away, Directors_meet, Robinson_back (comes to his senses), Robinson_takes (takes matters into his own hands), Directors_dividend (declare a dividend), Patterson_come, and Townsend_away.
Compounds and conditions: And(x,y) and If(...). We can express an “or” by splitting it into two rules, as below.
Smith_away ⟹ Townsend_away (alternatively, supply Townsend_away as a background fact)
Each rule can be encoded as Force(If α, Will β) or Force(α, β). For readability, we wrap a condition explicitly in If and mark what will happen or be inferred with Will. The result reads like the original wording: “If α, then β will follow.” At this stage we are giving natural language an executable skeleton. We name the participants, states, and relationships. The semantic expressions “if/then,” “and,” and “will” become constructors or rule entries. This step alone does not prove that the logic is correct.
7.2.5 Running the Inference: Propagation, Closure, and Termination
Put the observations taken as true, such as Jones_ill and Smith_away, into a set of known facts. Then run a small forward-chaining procedure:
Maintain Known, the set of observed or derived facts, and Agenda, the facts or conditions still to check.
Take an element x from Agenda:
If there is a rule Force(If a, Will b) and Known satisfies a (for example, a = And(p,q) and p,q ∈ Known), add Will b or b itself to Known and put consequences of b that remain to be checked on Agenda.
When you encounter And(u,v), put u and v on Agenda so that each subcondition can be checked or satisfied.
Continue until Agenda is empty and the computation has reached a fixed point.
The algorithm combines rewriting or propagation with a fixed point over a finite set. There are finitely many facts and rules. A rule only adds new entries and never removes an existing one, so the process is monotone and must terminate. This is the principle behind computing closure in Datalog. ADT constructors let us express the semantics in a form close to the original wording.
Semantically, firing a rule, adding its consequence, and repeating to a fixed point turns a readable natural-language skeleton into executable operational semantics. SOS and term rewriting supply the theoretical background. The engineering result we need is a small interpreter that terminates.
7.2.6 The Jones Problem Step by Step: Deriving the Dividend
The problem supplies the observations Jones_ill and Smith_away. Follow the propagation order from the preceding section:
The meeting: Jones_ill or Smith_away can trigger Directors_meet. There are two rules, and either one suffices.
Patterson comes → Robinson comes to his senses:
Jones_ill ⟹ Patterson_come ⟹ Robinson_back.
Townsend is away → Robinson takes matters into his own hands: if we model “inseparable” as Smith_away ⟹ Townsend_away, we obtain Robinson_takes immediately. Without that rule, we can supply Townsend_away as a background fact from the same context as Smith_away.
The necessary and sufficient condition for declaring the dividend:
And(Robinson_back, Robinson_takes) ⟹ Will(Directors_dividend). The preceding two steps establish both premises, yielding the desired conclusion.
We can do all this by reading the rules and propagating over data structures, without invoking the full machinery of first-order logic, resolution, or unification. We give up the generality and completeness guarantees of traditional Prolog SLD resolution in exchange for an expression close to natural language and a small, readable implementation. If needed, the rules can later be translated into Horn clauses for a more rigorous proof by SLD resolution.
7.2.7 What Makes the ADT Intuitive, Maintainable, and Reliable Enough?
Intuition. The constructors If, Will, and And express semantic elements of the story. A match branch says what to do when a particular sentence shape appears. Team members can read the AST like a passage of prose.
Maintainability. Add a construction such as Or, Unless, or UnlessIf, and the compiler’s exhaustiveness check can identify places that still need a case. This is easier to manage than scattered if-else statements.
Reliability. In this propositional setting, propagation is monotone and computes closure over a finite domain, so it terminates. This agrees with standard fixed-point semantics for Datalog. Stronger guarantees can be introduced incrementally, through equality and unification, conflict detection, or a treatment of confluence and termination in rewriting logic.
7.2.8 Natural Language to ADTs and Formal Logic to Theorem Proving
In principle, Montague semantics shows how far a formal account of compositional natural-language meaning can go, although implementing it is expensive. The ADT approach supplies an accessible, extensible working semantics. Encode the domain’s key sentence forms as constructors first, then add features such as Or, defaults, exceptions, time, or causation.
In practice, once a domain stabilizes and requirements grow, the same ADT can support both an interpreter that executes rewrites as operational semantics and a compiler front end that translates the AST to Horn clauses or Datalog. It can then use Prolog, ASP, or Datalog engines for their proof guarantees and ability to compute at scale.
7.2.9 Why Is This Practical Now?
Mature language support. F# and other mainstream languages give discriminated unions and pattern matching concise, safe, first-class support.
Firm theoretical foundations. Defining execution by a rewrite or transition relation is a basic technique of programming-language semantics. We translate it into a small kernel that a developer can implement.
Compatibility with traditional logic. The same knowledge can be mapped to Horn clauses and SLD resolution or to a Datalog fixed-point calculation for stronger proof guarantees and scalability.
The result is a readable, runnable, extensible prototype for intuitive inference: natural language → ADT sentence forms → pattern-matching rules → forward-chaining closure → conclusion. In teaching, prototyping, and many domain-bounded business rule systems, a small amount of code can produce an inference process that people can explain.
7.3 Implementations in F# and Swift
The AlgebraicCode repository contains implementations that express and solve the Jones Problem directly:
fsharp/JonesEngine.fsx — discriminated unions (ADTs), a forward-chaining kernel of about 40 lines, the Jones rules and facts, and code to run the example and print the result.
swift/JonesEngine.swift — the same kernel and example in Swift.
README.md — a one-line command to run the example and the expected output.
The implementation illustrates the preceding argument. We can use ADTs to make sentence forms such as If, Will, and And into a semantic skeleton, then use pattern matching and forward propagation (monotone closure) to carry out intuitive inference. F# discriminated unions and pattern matching fit this style directly. The propagation kernel computes a closure in the same fixed-point tradition as Datalog. For comparison with conventional logic, the same rules can be written as Horn clauses.
7.3.1 Running the Example
F# (cross-platform)
dotnet fsi fsharp/JonesEngine.fsx
Swift (use swiftc or the Swift REPL on macOS)
swift swift/JonesEngine.swift
The two files print the same derivation trace and final conclusion.
Expected output from both versions
Derived (step 1): The directors meet. ; Patterson comes. ; Townsend is away.
Derived (step 2): Robinson comes to his senses. ; Robinson takes matters into his own hands.
Derived (step 3): The directors declare a dividend.
✔ Goal reached: The directors declare a dividend.
All true facts:
- Jones is ill.
- Smith is away.
- Directors meet.
- Patterson comes.
- Townsend is away.
- Robinson comes to his senses.
- Robinson takes matters into his own hands.
- The directors declare a dividend.
7.3.2 How the kernel works
An ADT for the structure of a natural-language statement
The kernel needs only a few constructors.
Fact(id * text) represents an atomic fact with a human-readable description.
If of fact introduces a condition.
Will of fact introduces a conclusion or something that will happen.
And of fact * fact expresses conjunction.
Force of fact * fact defines a trigger rule: when the left side holds, assert the right side.
The constructors form a semantic vocabulary. Reading the AST is much like reading a sentence. F# discriminated unions and pattern matching make it natural to encode meaning in the shape of the data. The compiler’s exhaustiveness checks catch missing cases.
Translating the problem statements into rules
Jones_ill ⟹ Directors_meet
Smith_away ⟹ Directors_meet
And(Robinson_back, Robinson_takes) ⟹ Will(Directors_dividend)
Patterson_come ⟹ Robinson_back
Jones_ill ⟹ Patterson_come, following the 2023 erratum.
Townsend_away ⟹ Robinson_takes
Smith_away ⟹ Townsend_away models the statement that the two are inseparable.
Execution by forward chaining with a worklist
Maintain Known, the set of atomic facts given or already derived, and Agenda, the worklist of newly added facts.
For each Force(If α, Will β) rule, use structural matching to check α. An And holds when both operands satisfy the check recursively. When the condition holds, add the atoms asserted by β to Known.
Facts are added monotonically. Since both the set of possible facts and the rule set are finite, the process must reach a fixed point and terminate. This agrees with the least-fixed-point semantics of Datalog.
7.3.3 The core F# code
type fact = Fact of int * string | If of fact | Will of fact | And of fact * fact
type force = Force of fact * fact
let rec holds known = function
| Fact _ as f -> known.Contains f
| If g | Will g -> holds known g
| And(a,b) -> holds known a && holds known b
let step forces known =
forces
|> List.collect (fun (Force(cond,res)) ->
if holds known cond then
match res with
| Will (Fact _ as at) | (Fact _ as at) -> [at] // Assert atomic facts only
| _ -> [] else [])
|> List.distinct
|> List.filter (fun f -> not (known.Contains f))
let rec closure forces known trace =
match step forces known with
| [] -> known, List.rev trace
| newly -> closure forces (Set.union known (set newly)) (newly::trace)
Structural matching gives If, Will, and And their interpretation. These three forms suffice to solve the Jones Problem without a general-purpose first-order logic engine.
For a more formal treatment, compile the rules into Horn clauses and use SLD resolution to construct a proof.
7.3.4 Relation to formal methods and scope for extension
What it covers. At the propositional level, constructors for “if,” “and,” and “will” already express many business rules in a form people can read directly.
How it can grow. Add constructors and matching cases for disjunction, “unless,” defaults, exceptions, or time as needed. Exhaustiveness checking identifies the cases still to cover. The extended AST can then be compiled to Horn clauses or Datalog for stronger guarantees. Established frameworks such as term rewriting and structural operational semantics (SOS) can help analyze fixed points, termination, and confluence.
7.4 Compiling natural-language paragraphs into the Jones semantic ADT with GPT-4o
7.4.1 Approach and API choice
Structured Outputs. Azure OpenAI supports constraining model output to a JSON structure defined by a JSON Schema. For deployments or API versions that do not yet support this feature, JSON mode (response_format: {type: "json_object"}) can produce valid JSON, although the result is not guaranteed to match a particular schema.
API surface. This section uses the Chat Completions REST API with a system message and a user message. The request names the model by its deployment name, such as gpt-4o. To use the Responses API or AzureOpenAIClient/GetChatClient("gpt-4o") in the .NET SDK, adapt the request body to the corresponding official example.
7.4.2 System and user prompts for the LLM
System prompt for the required JSON output
You convert English paragraphs into input for a semantic ADT. Extract the following from the paragraph.
atoms is a table of atomic facts of the form {id, name, text}. Number the IDs from 1 to N, use Snake_Case for name, and make text a human-readable sentence ending in a period.
rules is a table of trigger rules. Each rule has the form { "if_all": [<atom.name>...], "then": "<atom.name>", "will": true }.
observations is a list of names of atoms that the paragraph explicitly identifies as true.
Mapping constraints
Do not use OR. If the paragraph says “P or Q -> R,” split it into two rules: [P] -> R and [Q] -> R.
Express conjunction with the if_all array. Put the conclusion in "then" and set "will": true.
Every name in rules[].then and rules[].if_all[] must occur in atoms[].name. Do not invent names in a rule.
The input is the Jones Problem. Use these suggested names wherever they apply.
Jones_ill, Smith_away, Directors_meet, Robinson_back, Robinson_takes, Directors_dividend, Patterson_come, Townsend_away.
Model “inseparable from” in the paragraph as Smith_away -> Townsend_away.
Return JSON only, with no surrounding text.
Example structure (illustrative, not the solution)
{
"atoms": [{"id":1,"name":"Jones_ill","text":"Jones is ill."}],
"rules": [{"if_all":["Jones_ill"],"then":"Directors_meet","will":true}],
"observations": ["Jones_ill","Smith_away"]
}
User prompt with the original problem statement
Turn the following paragraph into the JSON defined by the system instructions.
If you are told that Jones has fallen deathly ill and Smith has gone off to his bedside, you could determine if the directors will declare a dividend. If Jones is ill or Smith is away, then the directors will meet and declare a dividend if Robinson comes to his senses and takes matters into his own hands. If Patterson comes, he will force Robinson back to his senses but, of course, he will come only if Jones is ill. On the other hand, if Townsend, who is inseparable from Smith, stays away, Robinson will have to take matters into his own hands. Show that the directors will declare a dividend.
To process a Chinese paragraph, replace the English problem statement with its Chinese counterpart. The same prompt can produce JSON with the same structure.
7.4.3 Running the example
Code location
LLMJonesEngine.fsx
Before running the example, set these environment variables.
Set AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_API_KEY, and AZURE_OPENAI_DEPLOYMENT (the name of your GPT-4o deployment, such as gpt-4o). Optional settings are AZURE_OPENAI_API_VERSION (default 2024-08-01-preview) and USE_JSON_SCHEMA (1 requests Structured Outputs where available, with an automatic fallback to JSON mode).
This follows the Chat Completions and Structured Outputs conventions in the API documentation.
Expected output
The terminal prints a sequence of derivation steps ending with “✔ Goal reached: The directors declare a dividend.” If the input paragraph is in Chinese, the names remain in English Snake_Case and the descriptions become Chinese sentences. The inference process stays the same.
7.4.4 Reliability and extensibility
Why the sentences can be executed directly. Project each linguistic form onto an ADT constructor such as If, Will, or And. Compute the closure by forward chaining to a fixed point. At the propositional level the process is monotone over a finite set and therefore terminates. For stricter constraints, map the same JSON to Horn clauses or Datalog and use resolution or fixed-point semantics.
Structured Outputs and JSON mode. Structured Outputs uses JSON Schema to enforce constraints on fields and enumerated values. If a deployment lacks this feature, JSON mode with a prompt and example can guide GPT-4o toward the required structure until the deployment supports schema enforcement.
7.5 From an engineering approximation of compositional semantics to executable knowledge
7.5.1 What the example establishes
Compositional semantics holds that the meaning of a whole is determined by the meanings of its parts and how they combine. This chapter puts that principle into code. ADT constructors (If, And, Will, and others), pattern matching, and forward closure give the sentences in a paragraph an executable semantic structure. This retains the compositional insight of Montague semantics while limiting the formal machinery to what the application needs.
7.5.2 A repeatable three-step method
Sentence forms to ADTs. Map familiar forms such as “if … and … then …” to ADT constructors. The type defines the permitted shapes, and matching can be checked for exhaustiveness.
Rules to closure. Use monotone forward chaining to compute the least fixed point, as in Datalog, deriving the desired conclusion step by step. For the positive propositional fragment used here, termination and a unique closure are guaranteed.
LLM to JSON to ADT. With Structured Outputs or JSON mode, ask the LLM to produce {atoms, rules, observations}, then compile the result into the ADT and execute it. This automates the sequence from reading a paragraph to structuring its contents and drawing inferences. RAG can link results back to supporting evidence when needed.
7.5.3 Choosing this approach and extending it
Use the ADT approach for bounded domains with clear rules, especially where readers need to inspect, edit, and run them. Examples include teaching exercises, prototypes, and business-rule implementations.
Move to a restricted logic when the application needs standardized ontologies and automated reasoning. OWL 2 and its EL, QL, and RL profiles offer different trade-offs between expressiveness and efficiency, with established tool support. W3C
Support interchange. For sharing across systems, an interchange framework such as Common Logic (ISO/IEC 24707) can express mappings among dialects, carrying forward in standardized form the approach taken by KIF.
7.5.4 How this complements modern LLMs
RAG as nonparametric memory. Retrieving knowledge with a traceable source can substantially reduce hallucinations and make answers easier to substantiate. The Jones example binds evidence sentences to the rules used in the derivation.
A roadmap for LLMs and knowledge graphs. At scale and over time, three combinations are useful: knowledge-graph-enhanced LLMs, LLM-enhanced knowledge graphs, and joint reasoning. Graphs and ontologies impose structural constraints. The LLM helps extract, align, and complete the knowledge.
7.5.5 Reusable results of the chapter
A minimal working kernel with a fact/force ADT, the holds/step/closure operations for forward closure, and reference implementations in F# and Swift.
An automated path from an LLM through JSON and an ADT to inference, with optional export to Token KIF, OWL, or Datalog.
A replayable example for teaching and practice. The Jones Problem takes a natural-language statement through an explainable chain of inference to the declaration of a dividend.
7.5.6 Limits and precautions
The ADT-and-rules approach is a domain-specific engineering approximation with limits on expressiveness and completeness. Negation, defaults, time, or probability may call for stratification or translation to a more expressive restricted logic and its verifier.
When an LLM generates the rules, check the source evidence, validate the structure, and require a derivation trace that can be replayed.
7.5.7 Toward the final chapter
The final chapter returns to the main thread of the book: how algebraic code brings generation, composition, execution, and verification into a common structure. Natural language enters the system as a representation that can be parsed. Types and rules constrain that representation to form a program. Executing the program produces traceable results, which tests, evidence, or proofs can check. The path from language to knowledge to inference has become an engineering process that can be run and verified.
CHAPTER 8
Structure Defines the Boundary: From Algebraic Code to Verifiable Intelligence
Large language models have changed how programs receive input and generate candidates. The requirements for reliable software still hold. Data must have a recognizable shape, operations must follow explicit interfaces, composition must be explicable, and results must be reproducible and open to inspection. We began with tokens and arrived at a way of integrating generation into an engineered system, one that requires no special-purpose syntax.
8.1 Structure Goes Beyond Output Format
Writing model output as JSON does not by itself give us structure. Each field needs a defined role, each variant a closed boundary, and each composition a checkable contract. A result must be traceable to its inputs, its rules, and the steps that produced it. ADTs, pattern matching, functors, combinators, and computation graphs matter because they express in the program what counts as valid, whatever theoretical tradition they come from.
Likewise, a token in an engineered system is more than a string cut out by a model’s tokenizer. It should carry a type, a source, a scope, constraints, and whatever evidence is necessary. A downstream program can then decide whether two tokens may be combined, how each can be transformed, and when one must be rejected. Constraining free-form generation in this way turns a model’s capabilities into reusable software.
8.2 The Model Proposes and Structure Constrains
LLMs are particularly well suited to generating candidates, aligning meanings, and making local transformations. A model can map natural language to a function call, an ADT variant, or a graph node. It can also suggest an ordering among candidates. The model should not be the sole judge of validity. Type checking rules out malformed values. Pattern matching supports exhaustive case analysis. Lowering gives an abstraction a consistent implementation on a backend. Tests, rules, and evidence determine whether a result can be accepted.
This division of labor frees the model from the unrealistic demand that it always be right. It can propose freely while the system accepts cautiously. A failure now has a location: parsing, a type mismatch, conflicting constraints, a construct the backend cannot implement, insufficient evidence, or a failed acceptance check. Locating a failure gives us somewhere to start improving the system.
8.3 Composition Outlasts Scale
Models, frameworks, and hardware change. The laws of composition are comparatively stable. Kleisli composition sequences long-chain functions with effects. Applicative combines independent effects. An ADT expresses a closed set of states, node contracts connect a graph, and automatic differentiation uses forward and reverse transformations of the same computational relationship. Making these laws explicit frees the system from dependence on any one model version or runtime.
When designing an LLM system, look first for a small, stable algebraic interface. Adding prompts, layers of agents, or more models can come later. A smaller interface is easier to test. A closed set of variants is easier to cover exhaustively. Pure composition makes a computation easier to replay. Keeping evidence close to a result makes it easier to audit. Scale can raise the ceiling on capability. Structure determines whether that capability can be deployed safely.
8.4 Verify Before Accepting
Verification does not require a formal proof for every conclusion. Depending on the task, it may mean successful compilation, a type or shape check, unit tests, a numerical error bound, closure under a set of rules, citation coverage, or human review. What matters is that the system provides a criterion independent of linguistic fluency, before or after generation. A plausible sentence alone cannot show that a program runs, that the evidence is sufficient, or that a rule applies.
This gives a minimal meaning to “algebraic agent” as we use it here: an execution interface governed by types, operations, and laws of composition. A humanlike persona is incidental. Retrieval, inference, tool calls, and result rendering may all play a part, provided that they exchange structured tokens and leave a trace that can be reviewed. The value of an agent lies in its ability to turn a complex workflow into steps we can compose, observe, and check against acceptance criteria.
8.5 From the Printed Book to Running Code
The core edition keeps enduring material in the printed book and brings assignments, starter code, and acceptance criteria together at https://github.com/PanWuming/AlgebraicCode. The arrangement illustrates the book’s method. The printed text records lasting structures, while the repository carries implementations that need to run and evolve. From any chapter you can turn to the repository and use its tests to check your understanding of the corresponding contract.
If you carry away one way of judging a result, let it be this: ask what structure carries it, how that structure is composed and executed, and who will verify it. Large language models make generation inexpensive. Algebraic code helps us see the boundaries of correctness again. Reliable intelligence can give an answer and account for how it was constructed, executed, and verified.
References
[1] Abbott, M., Altenkirch, T., & Ghani, N. (2005). Containers: Constructing Strictly Positive Types. Theoretical Computer Science, 342(1), 3–27. https://doi.org/10.1016/j.tcs.2005.06.002
[8] Backus, J. (1978). Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs. Communications of the ACM, 21(8), 613–641. https://doi.org/10.1145/359576.359579
[9] Bahdanau, D., Cho, K., & Bengio, Y. (2015). Neural machine translation by jointly learning to align and translate. arXiv preprint, arXiv:1409.0473. https://arxiv.org/abs/1409.0473
[10] Baydin, A. G., Pearlmutter, B. A., Radul, A. A., & Siskind, J. M. (2018). Automatic Differentiation in Machine Learning: A Survey. Journal of Machine Learning Research, 18(153), 1–43.
[11] Bengio, Y., Simard, P., & Frasconi, P. (1994). Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks, 5(2), 157–166. https://doi.org/10.1109/72.279181
[13] Burstall, R. M., MacQueen, D., & Sannella, D. (1980). HOPE: An Experimental Applicative Language. Proceedings of the 1980 ACM Conference on LISP and Functional Programming. https://doi.org/10.1145/800087.802799
[14] Carion, N., Massa, F., Synnaeve, G., Usunier, N., Kirillov, A., & Zagoruyko, S. (2020). End-to-End Object Detection with Transformers. arXiv preprint, arXiv:2005.12872. https://arxiv.org/abs/2005.12872
[15] Chen, W., Ma, X., Wang, X., & Cohen, W. W. (2022). Program of Thoughts Prompting: Disentangling Computation from Reasoning for Numerical Reasoning Tasks. arXiv preprint, arXiv:2211.12588. https://doi.org/10.48550/arXiv.2211.12588
[17] Dai, Z., Yang, Z., Yang, Y., Carbonell, J., Le, Q. V., & Salakhutdinov, R. (2019). Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context. Proceedings of ACL 2019. https://aclanthology.org/P19-1285/
[18] Damas, L., & Milner, R. (1982). Principal type-schemes for functional programs. POPL ’82: Proceedings of the 9th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, 207–212. https://doi.org/10.1145/582153.582176
[19] d’Avila Garcez, A., & Lamb, L. C. (2023). Neurosymbolic AI: the 3rd wave. Artificial Intelligence Review, 56, 12387–12406. https://doi.org/10.1007/s10462-023-10448-w
[20] Dosovitskiy, A., Beyer, L., Kolesnikov, A., Weissenborn, D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer, M., Heigold, G., Gelly, S., Uszkoreit, J., & Houlsby, N. (2021). An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale. International Conference on Learning Representations (ICLR 2021). https://arxiv.org/abs/2010.11929
[21] Eilenberg, S., & Mac Lane, S. (1945). General Theory of Natural Equivalences. Transactions of the American Mathematical Society, 58(2), 231–294.
[22] Eilenberg, S., & Moore, J. C. (1965). Adjoint Functors and Triples. Transactions of the American Mathematical Society, 80, 246–285.
[23] Elliott, C. (2018). The simple essence of automatic differentiation. Proceedings of the ACM on Programming Languages (PACMPL), 2(ICFP), 1–29. https://doi.org/10.1145/3236765
[24] Ford, B. (2004). Parsing Expression Grammars: A Recognition-Based Syntactic Foundation. POPL ’04: Proceedings of the 31st ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, 111–122. https://doi.org/10.1145/964001.964011
[25] Gao, L., Madaan, A., Zhou, S., Alon, U., Liu, P., Yang, Y., Callan, J., & Neubig, G. (2022). PAL: Program-aided Language Models. arXiv preprint, arXiv:2211.10435. https://doi.org/10.48550/arXiv.2211.10435
[26] Gers, F. A., Schmidhuber, J., & Cummins, F. (2000). Learning to forget: Continual prediction with LSTM. Neural Computation, 12(10), 2451–2471. https://doi.org/10.1162/089976600300015015
[28] Gibbons, J., & Oliveira, B. C. d. S. (2009). The Essence of the Iterator Pattern. Journal of Functional Programming, 19(3–4), 377–402. https://doi.org/10.1017/S0956796809007291
[29] Goguen, J. A., Thatcher, J. W., Wagner, E. G., & Wright, J. B. (1977). Initial Algebra Semantics and Continuous Algebras. Journal of the ACM, 24(1), 68–95. https://doi.org/10.1145/321992.321997
[33] Graves, A., Fernández, S., Gomez, F., & Schmidhuber, J. (2006). Connectionist temporal classification: Labelling unsegmented sequence data with recurrent neural networks. Proceedings of the 23rd International Conference on Machine Learning (ICML ’06), 369–376. https://doi.org/10.1145/1143844.1143891
[34] Graves, A., Mohamed, A., & Hinton, G. (2013). Speech recognition with deep recurrent neural networks. 2013 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), 6645–6649. https://doi.org/10.1109/ICASSP.2013.6638947
[35] Greff, K., Srivastava, R. K., Koutník, J., Steunebrink, B. R., & Schmidhuber, J. (2017). LSTM: A search space odyssey. IEEE Transactions on Neural Networks and Learning Systems, 28(10), 2222–2232. https://doi.org/10.1109/TNNLS.2016.2582924
[36] Griewank, A., Kulshreshtha, K., & Walther, A. (2012). On the numerical stability of algorithmic differentiation. Computing, 94(2–4), 125–149. https://doi.org/10.1007/s00607-011-0162-z
[37] Griewank, A., & Walther, A. (2008). Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation (2nd ed.). Society for Industrial and Applied Mathematics (SIAM). https://epubs.siam.org/doi/book/10.1137/1.9780898717761
[38] Gu, A., & Dao, T. (2023). Mamba: Linear-Time Sequence Modeling with Selective State Spaces. arXiv preprint, arXiv:2312.00752. https://arxiv.org/abs/2312.00752
[42] Hoffmann, J., Borgeaud, S., Mensch, A., Buchatskaya, E., Cai, T., Rutherford, E., de Las Casas, D., Hendricks, L. A., Welbl, J., Clark, A., Hennigan, T., Noland, E., Millican, K., van den Driessche, G., Damoc, B., Guy, A., Osindero, S., Simonyan, K., Elsen, E., … Sifre, L. (2022). Training Compute-Optimal Large Language Models. Advances in Neural Information Processing Systems 35 (NeurIPS 2022). https://arxiv.org/abs/2203.15556
[43] Huang, L., Yu, W., Ma, W., Zhong, W., Feng, Z., Wang, H., Chen, Q., Peng, W., Feng, X., Qin, B., & Liu, T. (2023). A Survey on Hallucination in Large Language Models: Principles, Taxonomy, Challenges, and Open Questions. arXiv preprint arXiv:2311.05232. https://doi.org/10.48550/arXiv.2311.05232
[44] Huang, Y., & et al. (2024). A survey on retrieval-augmented generation for large language models. arXiv, 2404.10981.
[48] Hutton, G. (2016). Programming in Haskell (2nd ed.). Cambridge University Press.
[49] Ismayilzada, M., Circi, D., Sälevä, J., Sirin, H., Köksal, A., Dhingra, B., Bosselut, A., Ataman, D., & van der Plas, L. (2024). Evaluating Morphological Compositional Generalization in Large Language Models. arXiv preprint, arXiv:2410.12656. https://doi.org/10.48550/arXiv.2410.12656
[59] Kleisli, H. (1965). Every Standard Construction is Induced by a Pair of Adjoint Functors. Proceedings of the American Mathematical Society, 16(3), 544–546.
[61] Leijen, D., & Meijer, E. (2001). Parsec: Direct Style Monadic Parser Combinators for the Real World. Proceedings of the 2001 Haskell Workshop, 1–12.
[62] Leroy, X., Doligez, D., Frisch, A., Garrigue, J., Rémy, D., & Vouillon, J. (2025). The OCaml System: Documentation and User’s Manual. https://ocaml.org/manual/
[64] Liskov, B., & Zilles, S. (1974). Programming with Abstract Data Types. Proceedings of the ACM SIGPLAN Conference on Very High Level Languages. https://doi.org/10.1145/800233.807045
[65] Luong, M.-T., Pham, H., & Manning, C. D. (2015). Effective Approaches to Attention-based Neural Machine Translation. Proceedings of EMNLP 2015, 1412–1421. https://doi.org/10.18653/v1/D15-1166
[66] Mac Lane, S. (1963). Natural Associativity and Commutativity. Rice University Studies, 49(4), 28–46.
[67] Mac Lane, S. (1998). Categories for the Working Mathematician (2nd ed., Vol. 5). Springer.
[68] Maranget, L. (2007). Warnings for Pattern Matching. INRIA.
[90] Pan, S., Luo, L., Wang, Y., & others. (2024). Unifying Large Language Models and Knowledge Graphs: A Roadmap. IEEE Transactions on Knowledge and Data Engineering, 36(7), 3580–3599. https://doi.org/10.1109/TKDE.2023.3334770
[91] Paterson, R. (2007). Control.Applicative (Haskell Base Library) – Design Notes and Documentation.
[92] Pearlmutter, B. A., & Siskind, J. M. (2008). Reverse-Mode AD in a Functional Framework: Lambda the Ultimate Backpropagator. ACM Transactions on Programming Languages and Systems (TOPLAS), 30(2), 7:1-7:36. https://doi.org/10.1145/1330017.1330018
[93] Peyton Jones, S. L. (1987). The Implementation of Functional Programming Languages. Prentice Hall.
[94] Pierce, B. C. (2002). Types and Programming Languages. MIT Press.
[97] Reynolds, J. C. (1983a). Types, abstraction and parametric polymorphism. Information Processing 83, 513–523.
[98] Reynolds, J. C. (1983b). Types, Abstraction and Parametric Polymorphism. In R. E. A. Mason (Ed.), Information Processing 83 (Vol. 9, pp. 513–523). North-Holland.
[99] Robinson, J. A. (1965a). A machine-oriented logic based on the resolution principle. Journal of the ACM, 12(1), 23–41.
[102] Schuster, M., & Paliwal, K. K. (1997). Bidirectional recurrent neural networks. IEEE Transactions on Signal Processing, 45(11), 2673–2681. https://doi.org/10.1109/78.650093
[103] Shaw, P., Uszkoreit, J., & Vaswani, A. (2018). Self-Attention with Relative Position Representations. Proceedings of NAACL-HLT 2018. https://aclanthology.org/N18-2074/
[105] Syme, D., Petricek, T., & Lomov, D. (2007). Active Patterns in F#. Microsoft Research.
[106] The Rust Project Developers. (2025). Rust Compiler (rustc) and Language Documentation. https://www.rust-lang.org/
[107] Touvron, H., Lavril, T., Izacard, G., Martinet, X., Lachaux, M.-A., Lacroix, T., Rozière, B., Goyal, N., Hambro, E., Azhar, F., Rodriguez, A., Joulin, A., Grave, E., & Lample, G. (2023). LLaMA: Open and Efficient Foundation Language Models. arXiv preprint, arXiv:2302.13971. https://arxiv.org/abs/2302.13971
[108] Touvron, H., Martin, L., Stone, K., & et al. (2023). Llama 2: Open Foundation and Fine-Tuned Chat Models. arXiv preprint, arXiv:2307.09288. https://arxiv.org/abs/2307.09288
[111] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention Is All You Need. Advances in Neural Information Processing Systems 30 (NeurIPS 2017), 5998–6008. https://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf
[112] Vytiniotis, D., Weirich, S., Jones, S. P., & Washburn, G. (2006). Simple Unification-based Type Inference for GADTs. ICFP ’06: Proceedings of the 11th ACM SIGPLAN International Conference on Functional Programming, 50–61. https://doi.org/10.1145/1159803.1159811
[113] Wadler, P. (1989a). Theorems for Free! Proceedings of the Fourth ACM Conference on Functional Programming Languages and Computer Architecture (FPCA ’89), 347–359. https://doi.org/10.1145/99370.99404
[114] Wadler, P. (1989b). Theorems for Free!
[115] Wadler, P. (1992a). Comprehending Monads. Mathematical Structures in Computer Science, 2(4), 461–493.
[116] Wadler, P. (1992b). The Essence of Functional Programming. Proceedings of the 19th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL ’92), 1–14. https://doi.org/10.1145/143165.143169
[117] Wadler, P. (1995). Monads for Functional Programming. In J. Jeuring & E. Meijer (Eds.), Advanced Functional Programming (Vol. 925, pp. 24–52). Springer. https://doi.org/10.1007/3-540-59451-5_2
[118] Wei, J., Wang, X., Schuurmans, D., Bosma, M., Ichter, B., Xia, F., Chi, E. H., Le, Q. V., & Zhou, D. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. NeurIPS 2022. https://arxiv.org/abs/2201.11903
[119] Wei, J., Wang, X., Schuurmans, D., & others. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. arXiv preprint, arXiv:2201.11903. https://doi.org/10.48550/arXiv.2201.11903
[120] Weirich, S., Vytiniotis, D., Jones, S. P., & Washburn, G. (2006). Translating GADTs to System F. University of Pennsylvania.
[123] Wu, Y., Schuster, M., Chen, Z., Le, Q. V., Norouzi, M., Macherey, W., Krikun, M., Cao, Y., Gao, Q., Macherey, K., Klingner, J., Shah, A., Johnson, M., Liu, X., Kaiser, Ł., Gouws, S., Kato, Y., Kudo, T., Kazawa, H., … Dean, J. (2016). Google’s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint, arXiv:1609.08144. https://arxiv.org/abs/1609.08144
[124] Xiong, H., Wang, Z., Li, X., Bian, J., Xie, Z., Mumtaz, S., Al-Dulaimi, A., & Barnes, L. E. (2024). Converging Paradigms: The Synergy of Symbolic and Connectionist AI in LLM-Empowered Autonomous Agents. arXiv preprint, arXiv:2407.08516. https://doi.org/10.48550/arXiv.2407.08516
[125] Yao, S., Zhao, J., Yu, D., Du, N., Shafran, I., Narasimhan, K. R., & Cao, Y. (2023). ReAct: Synergizing Reasoning and Acting in Language Models. ICLR 2023. https://openreview.net/forum?id=WE_vluYUL-X
Subject Index
Entries are in alphabetical order. Select a section number to jump to its discussion. Chapter and front-matter references point to the corresponding heading.
Section numbers link to the text. The numbers after the dots are page numbers in this PDF edition.