← All articles

Type Systems for Machines That Program

Algebraic Data Types, Typeclasses, and verifiable architecture when the one writing the code is an agent

26 min readsoftware-architecturefunctional-programmingsoftware-designsystems-programmingprogramming-languages

Machine-translated from Spanish. Read the original

ByFederico Sawady O'ConnorRagnagrok Academy

For sixty years, the bottleneck in software was writing the code. That's why almost all our tools optimize for producing it, such as autocomplete, frameworks, scaffolding or snippets. But agents have just changed that equation, and generating larger volumes of code has become cheaper. What's expensive, what's scarce, what's valuable now is something else, trust. Assuming I know what I want to happen, how do I know that these thousands of lines an agent produced in minutes do what I think they do?

One of the software industry's classic answers is tests. And tests, which come in many kinds, are good. But we can't forget that a test is a sample, because it proves the code works only for the cases that an engineer or an agent wrote, under certain conditions. What's more, an agent that generates plausible-but-wrong code produces exactly the kind of error tests don't catch, the case nobody thought to sample.

The industry's other, newer answer is the harness, the layer of instructions, rules, and policies that surrounds the model and tells it what not to do — "don't use this API", "don't touch that folder", "don't make up dependencies", "don't push the code to production". It's useful, and today it's indispensable, but it shares the same underlying flaw as tests, just from the other side, because if a test is a sample of the correct cases we happened to think of, the harness is a list of the prohibitions we happened to think of. Both enumerate, and enumeration doesn't scale, because each rule covers the error you already imagined and none covers the one you didn't. Worse, the harness asks, it doesn't guarantee, since it relies on the model obeying a piece of text, not on the structure preventing the transgression. As agents gain autonomy and longer horizons, prohibition by enumeration becomes a game the rule-maker is always losing — there's always a missing rule, always a way to follow the letter and violate the intent. In the long run, telling the model what it shouldn't do isn't enough; we have to build a world where what it shouldn't do can't even be expressed.

In contrast to both approaches, we already have a tool that doesn't sample, that reasons by construction about entire classes of errors, and that happens to be — almost by accident — the best feedback mechanism an agent can have. It's a programming language's type system.

This article is a bet. The bet is that the tradition followed by languages like Haskell is not a mere academic curiosity that arrived too early. On the contrary, tools like algebraic types, typeclasses with laws, and rich type systems are technology waiting for a machine to be the one programming. And that this tradition doesn't stop at a single program, but scales all the way up to the architecture of a system.


The Compiler as Oracle

Let's think about what an agent needs to program well, and we'll see it isn't very different from what a human programmer needs.

First, it doesn't need infinite intelligence, but a feedback loop that is fast, total, and deterministic. Fast, so it can iterate many times. Total, because it has to rule on the entire space of possible inputs — at least for the class of errors the type is able to capture — not on a sample. Deterministic, so the same error produces the same correction.

A test suite can be fast, but it is by no means total. A human review could be total, but it's slow and nondeterministic. A type checker, though, is all three at once. In other words, when an agent writes ill-typed code, the compiler rejects the attempt with a structured, localized, reproducible error. The agent doesn't have to guess whether it got something wrong (and neither does a human), because it's told, precisely, in milliseconds.

This flips the usual relationship. It's true that, for a human, the type system sometimes feels like a bureaucrat asking for your papers, and a very complex one is annoying. But for an agent, the type system is a referee that corrects on the spot. The more expressive the type system, the more errors become compile-time errors, and the denser the signal guiding the agent toward correct code before it runs a single line.

The goal, then, is to move as many errors as possible from run time to compile time, using a range of tools from pure functional languages that we'll introduce along the way. The first, algebraic data types.


Making Illegal States Unrepresentable in the Program

The most powerful and most underrated idea in designing with algebraic types fits in one sentence, attributed to Yaron Minsky, which goes make illegal states unrepresentable — make illegal states impossible to even express.

Consider a network connection modeled the way almost anyone would model it by default, although this time we'll use Haskell as our notation:

data Connection = Connection
  { isConnected :: Bool
  , socket      :: Maybe Socket
  , lastError   :: Maybe Error
  }

This structure is easy to read, it follows a design we run into every day in the industry (a record with fields, some of them optional), and at the same time it's a trap. It's a trap because it allows states that make no sense, such as isConnected = True with socket = Nothing, that is, connected but with no socket; or connected and in error at the same time; or disconnected but with a live socket. There are actually 2 × 2 × 2 = 8 representable shapes, depending on the value of the boolean and on whether each Maybe holds something or not, and only a few of them are legal. Every illegal shape is a bug waiting for an agent — or a tired human — to write it. And in the industry, the combinatorics of most of the entities we deal with every day are even worse, because integers or strings are data types with (almost) infinite possibilities.

Correction (November 25, 2026). The first version spoke of 2 × 2 × 2 combinations. What's being counted is shapes, because each Just carries a socket or an error, so the record has many more values, and the illegal ones are many more too. I found it in a review of the series, and the repo lists the eight shapes, three of which are legal.

Is there an alternative? Yes, in algebraic jargon, a sum type (what shows up in other languages as enums with data, discriminated unions in TypeScript, sealed classes in Kotlin, or enum with associated values in Swift/Rust):

data Connection
  = Disconnected
  | Connecting   RetryCount
  | Connected    Socket
  | Failed       Error

Done this way, the impossible states are gone. Rather than being forbidden by a convention or policed by a test, they don't exist in the space of what can be expressed, because at any given moment you're either in one case with certain data, or in another with other data. No agent will be able to produce "connected without a socket", because it's inexpressible by design, and if it tries, it will be writing something that doesn't compile. The error is caught at the earliest and cheapest possible point, before the program runs and not while it runs.

As a second benefit, we get exhaustive pattern matching. If tomorrow I add a Reconnecting state, the compiler flags every place in the system that forgot to handle it. It's type-guided refactoring, where the tool walks you by the hand through every affected spot. For an agent modifying a large codebase, this is invaluable — it turns "did I forget a case?" from a nagging worry into a mechanical guarantee.

The other side of algebraic types are product types, structures that combine several fields at once, like the first Connection above. The problem was never the product itself, but the unconstrained product; and the cure is smart constructors combined with newtypes (new types that share another type's representation, but that the compiler won't let you mix with it). Instead of passing String everywhere — ending up with the infamous stringly-typed code — you can wrap the data in a type that can only be built by validating it up front:

newtype Email = Email Text          -- the constructor is not exported

data EmailError = InvalidEmail

mkEmail :: Text -> Either EmailError Email
mkEmail t
  | isValid t  = Right (Email t)
  | otherwise  = Left InvalidEmail

Once you have an Email — checked, say, at the program's boundary — you know it's valid, and that remains a guarantee throughout the rest of the program. In this case, the type becomes a proof that guarantees it. Alexis King, a well-known Haskell programmer, summed it up in the slogan parse, don't validate, one worth tattooing on yourself. In other words, don't check a raw piece of data every time you use it; transform it once into a type that makes the invalid data impossible from then on.

Correction (November 25, 2026). The first version called Alexis King a functional programming theorist, but she's a Haskell programmer. It also described newtypes as synonyms for another type, which is exactly what they aren't, because a synonym (type) is interchangeable with the original and a newtype is a distinct type the compiler won't let you mix with it. I found it in a review of the series.

Correction (November 2, 2026). The first version of this example returned Either Error Email and didn't declare InvalidEmail. Error is already the connection's error above, and further down it's the name of an effect, so the example now declares its own EmailError. I found it while turning the article into code that compiles. The repo has every example, and what shouldn't compile with the error it gets.


Typeclasses as Composable Contracts with Laws

And it doesn't end there. Algebraic types give you a vocabulary that invites you to design so that what shouldn't be expressible in a program can't be expressed. But typeclasses give you interfaces with laws, and laws are the ideal mechanism for making abstractions compose predictably.

For those unfamiliar with typeclasses, they represent ad hoc polymorphism (similar to interfaces in Java or other languages) and let you define operations that different types implement in their own way.

The most famous is probably Eq, which defines the equality operation that different types can implement:

class Eq a where
  (==) :: a -> a -> Bool

This operation lets you compare two values of the same type a and get a boolean result. But let's move to another example, less well known but more illustrative, Semigroup, which defines a combining operation:

class Semigroup a where
  (<>) :: a -> a -> a       -- combine two values into one

So far it's just like an interface in any language. What sets it apart is that the typeclass comes with a law that every instance must respect, associativity.

This law is expressed as follows, and it's a property that must hold for any instance of Semigroup:

(x <> y) <> z  ==  x <> (y <> z)

And this isn't as abstract as it sounds, because lists under concatenation, integers under addition (or under maximum) and dictionaries that merge are all semigroups. The instance for lists, for example, is nothing more than concatenation:

instance Semigroup [a] where
  (<>) = (++)        -- [1,2] <> [3,4] == [1,2,3,4]

Why does a law in an interface matter? Because it turns an informal promise into a verifiable contract, and because consequences follow from that contract for free. If your "combine" operation forms a semigroup, then — with no extra work — associativity lets you regroup computations at will, so you can parallelize the combination and distribute it across machines without changing the result. And if that operation is also commutative and idempotent, order and repetition stop mattering. That, at bottom, is what the theory of CRDTs rests on (the conflict-free replicated data types that make collaborative editors work), which says "find the right algebraic structure, and distributed consistency follows from well-known laws of abstract algebra".

So, for an agent, laws are gold for two reasons. First, they are generatable specifications, because from the associativity law you can automatically derive a property test (QuickCheck, Hedgehog) that exercises the implementation with hundreds of random cases. Second — though perhaps harder to see unless you're an expert in the subject — laws narrow the space of correct implementations, since there are many ways to write an operation a -> a -> a for a concrete type, such as Int -> Int -> Int, but few that are also associative. This lets the agent prune the search tree of correct implementations.

Correction (November 25, 2026). The first version spoke of a function of type a -> a -> a without saying for which a. If a is polymorphic, there are only two total functions of that type, the one that returns the first argument and the one that returns the second, and both are associative. The law restricts something when the type is concrete, and the repo has a Semigroup that averages, compiles and isn't associative. I found it in a review of the series.


The Big Leap from Program to System

This is where most discussions about types stop, and where things get interesting. If we put agents to work programming at higher levels of abstraction, the advantages presented so far apply to specific functions, to an entire module, or to a complete program — all of which are still units of code. An interesting question, though, is whether the same discipline scales to the architecture of a system that brings those units together somehow, such as the boundaries between services, the protocols they use, the forms of configuration that live outside them, the pipeline that deploys new versions of the system, and so on.

What's the bet in this case? The translation is direct and worth stating as a principle:

At the program level, types make illegal states unrepresentable. At the system level, types make illegal interactions unrepresentable.

Let's look at some concrete mechanisms.

A very illustrative one is defining protocols as typed state machines. A protocol is a legal sequence of messages, where you can't send data before the handshake or close a connection twice. If we add techniques like phantom types or GADTs to algebraic types (mechanisms for carrying extra information — in this case, the protocol's state — up to the type level), it becomes possible to encode that state in the type, so that illegal transitions don't compile:

data Door (s :: DoorState) where
  MkDoor :: Door s

newDoor :: Door 'Closed
newDoor = MkDoor

open  :: Door 'Closed -> Door 'Open
close :: Door 'Open   -> Door 'Closed

The trick is the same as with smart constructors (MkDoor isn't exported), so a new door comes from newDoor, always closed, and after that it only changes through open/close, in such a way that the state annotated in the type ('Open, 'Closed) always reflects the real state. With this design — which, admittedly, requires a more expressive type system — trying to open an already open door is a type error. Taken to the extreme, this technique is known as session types, where the entire protocol between two services becomes a type, and a client that violates the choreography doesn't compile. And it bears repeating that such a client (a program), put through the static check of a type system with the right rules, is guaranteed not to compile. This way, the "API contract" stops being a PDF someone ought to read, or even a JSON spec an agent ought to follow, and becomes something a machine formally verifies.

Correction (November 2, 2026). The first version had no newDoor. With the constructor unexported, open and close both need a door that already exists, so there was no way to get the first one. Now newDoor is the only way in, and it hands you a closed door.

In the repo I wrote exactly that, open (open newDoor), and GHC 9.12 rejects it like this:

rejected/OpenTwice.hs:9:13: error: [GHC-83865]
    • Couldn't match type ‘Open’ with ‘Closed’
      Expected: Door Closed
        Actual: Door Open
    • In the first argument of ‘open’, namely ‘(open newDoor)’
      In the expression: open (open newDoor)
      In an equation for ‘bad’: bad = open (open newDoor)
  |
9 | bad = open (open newDoor)
  |             ^^^^^^^^^^^^

The error says what it expected (a closed door), what it got (an open one) and where, by line and column. It's the fast, localized signal I talked about at the start, and it arrived without running anything or writing a test.

And what about things like having permission to read a database's configuration? The answer is encoding effects in the type. In most languages, looking at a function's type doesn't tell you whether it will read the database, call another service over the network, or even launch missiles — a running joke in the Haskell community, though these days it's stopped being a metaphor. With an effect system, we can encode the following:

fetchUser :: Members '[Reader DbConfig, Error NotFound] r
          => UserId -> Eff r User

The type of fetchUser declares exactly what this function can do, namely read database config and fail with "not found". And it cannot send emails or write files, because those effects aren't in its type. At the architecture level this is huge, because the capabilities of each component are documented and verified in its type. And an agent that tries to sneak a network call into a "pure computation" function (i.e., one without effects) runs straight into the type. The security review question "can this module do X?" goes from a manual (or automated) audit to a static check at compile time.

Clarification (November 2, 2026). The signature uses the syntax of the freer-simple library, which doesn't build with current GHC (9.12). The repo implements the minimum of that interface, in about a hundred lines, so the signature compiles as written. In a real project, a maintained library like effectful says the same thing with different syntax ((Reader DbConfig :> es, Error NotFound :> es) => UserId -> Eff es User).

In the repo there's a fetchUser' with the same signature as fetchUser, which sends an email with sendEmail before looking up the user. GHC rejects it at the line of the call (I trim the middle of the message):

rejected/SneakEmail.hs:12:3: error: [GHC-39999]
    • Could not deduce ‘Member SendEmail r’
        arising from a use of ‘sendEmail’
      from the context: Members [Reader DbConfig, Error NotFound] r
    …
   |
12 |   sendEmail "attacker@example.com" "here's the db config"
   |   ^^^^^^^^^

The message names the missing effect (SendEmail) and the ones the signature does allow. To make it compile you have to add that effect to the type, and that change is in plain view of whoever reviews the signature.

And there's much more to explore, like typed configurations (valuable in distributed systems), or even microservice architectures as types (where each service is a type with its own laws, and composing services becomes composing types). But for now, what matters is that the same "make the illegal unrepresentable" principle we apply to individual functions can be applied to the entire architecture of the system, guaranteeing that whole classes of errors, by design, can't even be expressed. This is, essentially, the program of Scott Wlaschin's Domain Modeling Made Functional, scaled up, where you model the domain — and then the system — with types so precise that incorrect code becomes literally inexpressible.

Although these ideas aren't all that mainstream, systems languages like Rust take these mechanisms down to the metal, and its ownership system is a type system that makes entire classes of memory and concurrency errors unrepresentable, at compile time, without a garbage collector.


The Big Bet Is the Typed Agentic Loop

Let's put the pieces together. What does an agent programming under this regime actually look like? Clearly it's not "the agent spits out code and we pray". It's a loop with guardrails at every step.

1. Specification as type, first. Before implementing, the agent (or a planning agent) writes the type of the units of code it's going to implement. That is, the type becomes the specification. A function parse :: Text -> Either ParseError Ast declares its contract before it exists. In rich type systems, the type alone rules out most wrong implementations; there's even the folklore that "if it type-checks, it's probably correct", which parametricity ("theorems for free", from Wadler — the idea that the type of a generic function constrains what it can do so tightly that certain properties are proven just by looking at the signature) makes rigorous for polymorphic functions, because the type constrains behavior so much that certain properties follow for free from a function's type.

Correction (November 25, 2026). The first version of this signature returned Either Error Ast, with the same ambiguous name that the November 2 correction had already removed from the Email example. It now uses its own ParseError. I found it in a review of the series.

2. Type-directed synthesis and search. The agent doesn't search in a vacuum. Tools like Hoogle let you search for useful functions simply by their type. And typed holes (a mechanism used in Haskell to leave a gap to be filled in later) let the agent write _ in the middle of an expression and ask the compiler "what type goes here, and what do I have available that produces it?". Type-directed synthesis (the line of work behind Synquid, Idris's proof search) turns a type-specification into implementation candidates. The agent's search space is pruned by the type at every step.

3. Generate, compile, refine. The agent proposes, the compiler disposes. Every ill-typed attempt comes back with a structured error the agent uses to correct itself. It's the oracle loop we talked about, fast, total and deterministic.

4. A second gate, with refinements and properties. Basic types don't capture everything. "This list is sorted", "this index is in range", "this function terminates" require more. This is where refinement types come in (Liquid Haskell, where a type carries a logical predicate checked by an SMT solver — an engine that automatically decides logical formulas) along with dependent types (Idris, Agda, where types can depend on values). The agent encodes pre- and postconditions, and an automated verifier checks them. Whatever doesn't make it into the type is covered by property tests derived from the laws.

5. The culmination is that the agent builds its own validation. This is what sets mature agentic development apart. The agent doesn't just write code that passes the existing checks; it builds the checks. When it models a new domain, it emits, alongside the code, the smart constructors that guard the boundaries, the typeclasses that encode the domain's laws, the instances that satisfy them, the QuickCheck properties that test them, the refinement predicates, and when needed, small formal proofs (Liquid Haskell, Idris, Dafny, F*, Lean). The verification harness becomes a first-class deliverable, not an appendix. And since that harness is itself typed and compiled, it can't silently lie.

Imagine an agent you ask for an accounting-balances subsystem. Instead of handing back functions and a few example tests, it hands back a sum type for account transitions in which illegal transitions don't compile; a commutative semigroup instance for combining ledgers, with its associativity and commutativity laws; a property test proving that merging replicas converges regardless of order; and a refinement guaranteeing that no balance goes negative without an explicit overdraft entry. "The code" and "the proof that the code is correct" arrive in the same commit, and both compile.


Honesty About the Costs of the Bet

It would be dishonest to sell this as free. It has real friction, and it's worth naming.

Rich type systems have a steep learning curve — although, curiously, the agent absorbs it better than many humans, because for the agent the compiler is a signal, not a scolding. There's also a trade-off between expressiveness and decidability, which those of us who spend our time reasoning about type systems know very well. The more you want to express in a type, the closer you get to dependent types, where an automatic type inference mechanism is no longer decidable, which means more effort goes into verification. In other words, not every property is reasonably expressible as a type, and things like "this machine learning model is fair" or "this UI is pretty" aren't easily specified this way.

Types also lie if the program uses escape hatches that switch off the checker. Haskell, for instance, has unsafePerformIO, which skips effect tracking; TypeScript has any, which disables type checking; and Rust has unsafe blocks, which let you dereference raw pointers that the borrow checker doesn't track. And an agent facing a weak type system on the other side of the compiler can fool the checker instead of satisfying it — which is why the strength of the type system matters, and why banning escape hatches in generated code is a sensible policy.

Correction (November 25, 2026). The first version said Rust's unsafe blocks suspend the borrow checker's guarantees. They don't, because the Rust book makes clear that unsafe doesn't turn it off, and a reference inside the block is still checked. What it enables are operations the compiler doesn't verify, like dereferencing a raw pointer, so it's still an escape hatch and the conclusion doesn't change. I found it in a review of the series.

And there's always the boundary with the untyped world, such as the network, the disk, JSON or user input. There, no types hold until you parse. That's why parse, don't validate is the discipline of the boundary, in which you concentrate the uncertainty in a thin, well-guarded edge, and leave the interior of the system demonstrably sound.

Even so, we don't think any of these objections sinks the bet. They just mark out where it pays off, and it pays off in domain logic, protocols, boundaries, and invariants, which is exactly where agents produce the most expensive and subtle bugs.


Toward a Provable Architecture

There's a symmetry worth seeing in full. For decades, expressing complex types in advanced type systems was a luxury, because you paid a design cost up front to avoid bugs that a disciplined human could, with luck, avoid in other ways (unit testing, etc.). That meant the math didn't always add up, which is why most software is written in loose languages (like Python, Ruby, PHP, or JavaScript), though some niches took advantage of languages like OCaml, Haskell, or Scala to implement some part of their systems (companies like Jane Street, IOHK, NoRedInk, etc., just to name a few).

But this article tries to show that agents break that symmetry. When abundant code is cheaper, the cost of designing good types is amortized over an enormous amount of generation, and the benefit — rejecting by construction whole classes of errors that no test would ever sample — is multiplied. The type system stops being the human's bureaucrat and becomes the machine's specification language and safety fence.

Human work is already being pushed upward, and we no longer write every function. These days we find ourselves declaring intentions through various forms of specification. So, I ask myself, why not do it in the form of properties or laws, declaring which states are legal, which interactions make sense, which invariants must never be broken? The agent inhabits that bounded space, explores freely, and can't fall off, because the compiler is a safety fence. Verification, for the first time, scales at the same pace as generation — because a good part of it is generated and checked by the machine itself.

The functional tradition — algebraic types to make the illegal unrepresentable, typeclasses with laws to compose with confidence, rich type systems to push errors up to compile time — seemed ahead of its time. Maybe it wasn't ahead of its time. Maybe it was waiting for the programmer to be a machine that needed, more than anyone, for the truth about code to be mechanically verifiable.

The founders of Haskell were right. As early as 1989, John Hughes, one of them, was arguing in Why Functional Programming Matters why this way of programming mattered. It's just that the audience these concepts serve best has only just arrived, it's artificial, and it's the one that most needs to take advantage of them.


References

The code

Everything this article claims, in code that runs. Clone it, break it, open an issue.

Ragnagrok/type-systems-for-machines-that-program
Support the blog

If this article was useful to you, you can sponsor the blog on GitHub. It helps me keep writing.