← All articles

Building or Pruning the Infinite

Induction, coinduction, and why vibecoding and spec-driven development are the two halves of the same pattern

20 min readfunctional-programmingsoftware-engineeringartificial-intelligenceprogramming-paradigmscomputer-science

Machine-translated from Spanish. Read the original

ByFederico Sawady O'ConnorRagnagrok Academy

A few days ago I caught myself trying to put a name to an intuition. I feel there are two ways of programming. One is the usual one, where you start from base cases and build, piece by piece, until you get to what you want. The other is almost the reverse. You start from something infinite—even something fuzzy, fluctuating between probabilities—and you refine it, trim it and add detail until what you want comes out of it.

The first one we teach in every course. The second, very few people have a handle on. And yet I think it's the one that best describes what's happening today when we program with language models.

To think it through, I used the smallest example I could come up with, the number two.

Two ways to get to two

In Haskell, the naturals can be defined with two constructors, zero and successor.

data N = Z | S N

dos :: N
dos = S (S Z)            -- I build it: from the base, up to where I want

That's dos (Spanish for two), the constructed two. You start from Z, apply S twice, done. Nothing exists until you put it together.

But there's another way to reach the same value:

nats :: [N]
nats = iterate S Z       -- all the naturals: a list that never ends

dos' :: N
dos' = head . tail . tail $ nats   -- I don't build two: I observe it

Here I didn't build two. I described all the naturals—an infinite object that, thanks to lazy evaluation, “exists” without anyone ever finishing computing it—and then I observed it. I took the tail twice and looked at the head. dos and dos' are the same value, but they got there by opposite paths.

The same thing happens with the even numbers (pares; esPar means “is even”), and an interesting nuance shows up:

esPar :: N -> Bool
esPar Z         = True
esPar (S Z)     = False
esPar (S (S n)) = esPar n

pares, pares' :: [N]
pares  = iterate (S . S) Z    -- I generate exactly what I want
pares' = filter esPar nats    -- I start from everything and keep what's useful

pares is still a construction, albeit an infinite one. pares' is something else. It's selecting within a space that already contains everything. I don't tell it how to build an even number; I tell it how to recognize one.

It's not a stray intuition but a duality

The first thing I wanted to know was whether this had been formalized. It has, quite thoroughly.

On the construction side there are inductive data. Values are built from base cases with constructors (Z, S) and consumed with structural recursion, that is, with a fold. Formally they are initial algebras, the smallest type closed under its constructors.

On the observation side there are codata. Values can be infinite and are defined not by how they are built but by what you can observe of them (head and tail, exactly the two observations I used to reach dos'). They are produced by corecursion, that is, with an unfold. Formally they are final coalgebras, the largest type compatible with those observations.

Building from the base Refining from the whole
induction coinduction
data, initial algebra codata, final coalgebra
fold (catamorphism) unfold (anamorphism) plus selection
synthesis generate and prune
dos = S (S Z) dos' = head . tail . tail $ nats

There's a detail that reinforces the point. In Haskell, because of lazy evaluation, N isn't even purely inductive, because infinito = S infinito is a perfectly valid value. Languages like Agda or Coq explicitly separate inductive and coinductive types precisely because that boundary matters when it comes to reasoning.

And the most important thing about coinduction, for what comes next, is its principle of equality. Two coinductive objects are equal if no possible observation tells them apart. It's called bisimulation. Hold on to that idea.

Generate and prune

The other half of the intuition—starting from the whole and cutting it down—also has its tradition, and its founding text is one I've already cited in this series, Why Functional Programming Matters, by John Hughes (1989).

Hughes argues that lazy evaluation lets you separate generating a space of possibilities (an infinite sequence of approximations, a complete game tree) and selecting within it (taking until it converges, pruning the branches that are no good), two things we almost always program tangled together. His examples—Newton-Raphson, numerical integration, minimax with alpha-beta pruning—all have that shape, with a generator that doesn't know what it's being used for and a consumer that decides how much to look at.

Philip Wadler carried the idea over to search in How to Replace Failure by a List of Successes (1985). Instead of a computation that either fails or succeeds, you represent all possible solutions as a list, potentially infinite, and keep the ones that qualify. It's the seed of the list monad and of the generate and test style. Logic programming (Prolog, miniKanren) is the same idea turned into a language, where you declare the space and the engine constrains it.

The “fluctuating between probabilities” part has a name too, and it's called probabilistic programming. You write a prior distribution over a huge space, condition on what you've observed, and get a sharper posterior distribution. There, refining is literally conditioning.

And at the level of specifications there's the refinement calculus (Wirth in 1971, later Morgan, Back and von Wright), where you start from a nondeterministic specification, which admits a vast number of behaviors, and each step makes it more concrete. The crucial thing about refinement is that each step preserves correctness, meaning the refined program does only things the specification allowed, and terminates wherever the specification required it to.

Correction (November 25, 2026). The first version said the refined program does everything the specification allowed. It's the other way around, because refining shrinks the set of behaviors, so the program does only some of the allowed things. What it can't lose is termination wherever the specification requires it. I found it in a review of the series.

In the denotational twist, the two faces mirror each other

There's a further twist I especially like, because it connects with the denotational perspective that runs through this series.

In domain theory, an infinite value like nats is understood as the limit of increasingly defined finite approximations:

⊥  ⊑  Z : ⊥  ⊑  Z : S Z : ⊥  ⊑  Z : S Z : S (S Z) : ⊥  ⊑  …

Each step carries a little more information than the one before, and ⊥ is total ignorance. In other words, in the semantics, “refining the infinite” is formalized underneath as the incremental construction of information. The duality is real, but it isn't a chasm, because the two ways of programming are two ways of traversing the same order.

And that order, ⊑, is monotonic. Information you already had is never lost. Keep this in mind too.

An LLM is the second way of programming

Back to practice. A language model doesn't build a program from base cases. It is, almost literally, the second way of programming turned into a machine:

  • It's a distribution over all possible programs. An infinite space, fluctuating between probabilities. Exactly the starting point of the intuition.
  • The prompt is conditioning. You start from a gigantic prior (“any text”) and every word you add trims the space.
  • Generation is an unfold. It produces token by token, and each observation conditions the next. It's pure corecursion, with no base case, just a repeated step until something decides to stop.
  • Reviewing the result is the filter. You run it, look at it, accept it or ask for something else.

In Hughes's terms, the model is the lazy generator and you are the one doing the pruning (muestras = samples, meGusta ≈ “I like it”):

programa = head . filter meGusta $ muestras llm prompt

Vibecoding and spec-driven, read through this lens

With this vocabulary, the debate that's still open in the industry sorts itself out quite a bit.

Spec-driven development resembles the refinement calculus, because you write the specification first and ask the agent to make it concrete. With LLMs, in practice, that spec ends up being a long prompt with which you condition everything up front, blindly.

Vibecoding is interactive conditioning. You generate, observe, correct, generate again. The program ends up defined by its observable behavior, not by a prior description. It's coinductive in spirit (if it behaves well in everything I looked at, it's the program I wanted).

And for now, in many contexts, vibecoding has the upper hand. A few months ago, in Tension in Software Design: Why Specifying More Isn’t Specifying Better, I went over some unhappy results from SDD. Now I think I understand better why.

Generating has become almost free. Hughes showed that laziness made the “generate and prune” style modular. LLMs take it to the extreme. If a sample costs seconds, exploring comes out cheaper than specifying.

Often you don't know what you want until you see it. A spec demands knowing the requirement in advance. Observing lets you discover it. It's the difference between defining something by construction and defining it by how you react to it.

Conditioning while looking at the output is more informative. A spec written beforehand conditions blindly. In vibecoding, each correction responds to what actually came out and points right at where the distribution got it wrong. It's active learning versus passive sampling.

A prose spec loses its only advantage. The value of a formal specification is precision. A natural-language spec for an LLM is still ambiguous, so you pay the cost of specifying without getting the guarantee. It ends up being a longer prompt, not a contract.

Where it loses, in the bisimulation nobody does

But here's where the idea I asked you to hold on to comes back. Coinduction proves equality by bisimulation, under which two things are equal if they agree on all possible observations. A human reviewing makes a handful.

So vibecoding produces programs that pass everything you looked at and may fail at everything else, such as edge cases, security, concurrency or invariants that don't show up on screen. It's overfitting to the observer. The program didn't learn to be correct; it learned to look correct to you, in the three checks you ran.

And there's a second, subtler difference, which has to do with monotonicity. In the refinement calculus, each step preserves correctness, so you never break what you already satisfied. In vibecoding, each new round of conditioning can break earlier properties without you noticing, because nobody is watching them. It isn't refinement but a walk through the distribution. And that is, formally, where regressions come from, along with a good chunk of the technical debt I talked about in “Code Is Cheap”: The Modern Fallacy That Could Cost a Fortune.

A detour through physics

At this point an almost inevitable temptation appears, that of seeing in all this the old fight between Einstein's physics and quantum mechanics. Deterministic versus probabilistic. Some of that holds up, but the good parallel isn't where it seems to be, and it's worth separating what is structure from what is metaphor.

Laplace versus the lab

The underlying opposition isn't relativity versus quantum, but classical versus quantum physics. Relativity is the most refined classical theory we have, with well-defined states, deterministic evolution and no chance whatsoever. Einstein's “God does not play dice” goes along those lines.

That classical ideal, taken to the extreme, is Laplace's demon, the idea that if you know the law and the initial conditions, everything else can be deduced. It's spec-driven development in its purest form, where you write the law (the spec), fix the starting point, and the program comes out by derivation.

Vibecoding, on the other hand, resembles experimental physics. You don't know the law, so you probe the system, observe, and adjust your description according to what you see.

Einstein and the clocks

And here's a twist I love. The 1905 special relativity paper opens with an observational move. Einstein doesn't define simultaneity as a metaphysical fact, but through a procedure, that of synchronizing clocks with light signals. What can't be measured doesn't get into the theory. Heisenberg later said that for his matrix mechanics he took inspiration from that attitude of speaking only of observable quantities.

It's a coinductive move in spirit. The system is what you can observe of it, and two things that no experiment can tell apart are the same thing. Bisimulation is the formal version of that principle, which in philosophy has a name of its own, Leibniz's identity of indiscernibles. Relativity has classical mathematics but an observational epistemology, and that epistemology is the bridge to quantum mechanics.

The anecdote has a punchline. According to Heisenberg himself, when in 1926 he told Einstein he had taken that idea from him, Einstein replied that he no longer held it, and that “It is the theory which decides what we can observe.” Keep that line in mind; it comes back in a bit.

So as not to cheat with my own table, I'll clarify that classical dynamical systems—initial state plus law of evolution—are the textbook example of a coalgebra. “State → next state” is an unfold. So Einstein's physics doesn't fall on the inductive side of the dichotomy. The induction/coinduction axis and the classical/quantum axis don't line up. The ones that do line up are two others (deterministic versus probabilistic, and the state as a thing versus the system defined by what is observed).

It isn't quantum

The second caveat is more important. An LLM's probability is not quantum. A language model is a deterministic function that produces a classical distribution, with no amplitudes canceling each other out, no interference, no entanglement. Talking about “collapse” when you sample is a pretty metaphor that confuses more than it clarifies.

It's Boltzmann

If you're looking for real physics behind an LLM, it's in Boltzmann, not in Heisenberg. And it's not an analogy but the same math.

The temperature softmax the model uses to pick the next token is the Boltzmann distribution (or Gibbs distribution):

p(i) = exp(z_i / T) / Σ_j exp(z_j / T)

The logits z play the role of energy with the sign flipped, and the temperature T is called that because it is, literally, the one from physics. At zero temperature, the model always lands in the most probable state—the ground state, what machine learning calls greedy decoding. At high temperature, it becomes disordered.

But the parallel that matters isn't the formula but the reason statistical mechanics was born. It was born because it became impossible to track every molecule. The microscopic dynamics was still deterministic, but there were too many particles, so people switched to describing the system by what can be measured in aggregate, such as pressure, temperature or energy.

Entropy is going to grow

With software we're reaching that point, and it's worth saying plainly. We won't be able to read every line. Not out of laziness, but because generating has become faster than reading, and that gap only widens. It's the same asymmetry It’s Not a Wall, It’s a Confession closed on, the one where verification hasn't scaled at the pace of generation.

And the system's entropy is going to grow. That isn't pessimism either, but rather the second law of thermodynamics. In an isolated system entropy doesn't go down, and no physicist sets out to defeat it.

To see what that word means in code, Edwin Jaynes helps. In 1957 he showed that statistical mechanics can be read as inference, and that entropy measures uncertainty, that is, how many microscopic states are compatible with what you know about the system. It's the same idea that runs through this whole article—the prompt as conditioning, refining as gaining information—now from the reviewer's side. Applied to code, the question is how many different programs are compatible with what you know about yours. With thousands of lines nobody has read, that's a huge number, every program that looks like it works.

Every type, every invariant, every property you add rules out part of those possible programs. It doesn't tidy up the code line by line, but rather narrows down what can be going on inside, without you having to look.

Noether and what is conserved

If entropy is going to grow anyway, the question stops being how to avoid it and becomes what holds up in spite of it. The answer physics gives is conserved quantities. The energy of an isolated gas stays the same even if you don't know where a single one of its molecules is. Emmy Noether showed in 1918 that those conservation laws follow from the system's symmetries, not from the detail of each trajectory.

The software equivalent is invariants. When you can no longer read every line the model generated, what you have left are the properties that must hold no matter what happens in the detail, such as representation invariants, contracts and executable properties. They are the program's conservation laws, rules that hold even when you're not looking.

Vibecoding without invariants is doing thermodynamics without conservation of energy, because you can observe a great deal, but nothing guarantees you anything beyond what you observed.

The spec as a filter, not a blueprint

Those conservation laws have to live somewhere. And that, I think, is the way out, which is not picking a side but relocating the spec. Instead of using it to build—the blueprint the agent has to follow—use it to select—the filter (cumpleSpec, “meets the spec”) that prunes what the agent generates:

programa = head . filter cumpleSpec $ muestras llm prompt
  where
    cumpleSpec p = tipa p && pasaTests p && cumplePropiedades p

And for that to work, the ideal spec isn't a prose document. It's something that runs:

  • Types, which are the first and cheapest filter. The generator can write a program that uses an illegal state, but if that state can't be expressed, the program doesn't typecheck and is thrown out without running it. It's Einstein's answer to Heisenberg applied to code, where the theory decides what can be observed. That's what Type Systems for Machines That Program was about.
  • Property-based tests (QuickCheck, Hypothesis, fast-check), which automate coinductive observation and make thousands of observations instead of the three you make. It's not full bisimulation, but it gets much closer than your eye does. It's the harness from QuickCheck vs. Traditional Testing as a Deterministic Harness in the GenAI Era.
  • Formal verification, where it's worth it, which turns “all observations” from an aspiration into a guarantee.

Correction (November 25, 2026). The first version said types constrain the space before generating, and that the generator never even visits the branches with illegal states. That's not so, because the model generates those programs anyway and the type check throws them out afterwards, as tipa p does in the filter above. The repo shows it, because of 869,285 candidates up to size 7 only 33,250 typecheck. The argument doesn't change, and I found it in a review of the series.

There's one more thing that strikes me as the nicest part of all this. A filter like that doesn't just prune, but gives the process back its monotonicity. Every property you add to the suite stays there for good. The set of acceptable programs can only shrink, never grow through carelessness. The random walk of vibecoding, passed through a filter that accumulates properties, becomes a refinement again, and you get the ⊑ back. It's a ratchet. The generator can go wherever it likes; what gets accepted only moves forward.

In the repo the ratchet can be counted. I enumerate every candidate program up to size 7 for the question “is x even?” and pass them through the filters, one after the other:

869285 candidates up to size 7
33250 typecheck
194 also pass 0, 1, 2; 78 of them are wrong
116 also satisfy the properties; 0 of them are wrong

Each filter only removes candidates, it never adds any. What interests me most is the third line, because of the 194 programs that pass the three tries I'd make by eye (0, 1 and 2), 78 fail on some number up to 1,000. The first one that filter accepts is not (x == 1), which is wrong at 3. That's overfitting to the observer, counted. With the properties that define an even number, 116 are left, and none of them is wrong.

Hughes's two halves

In From Invention to Deduction: Reclaiming Engineering in the GenAI Era I set vibe coding, which asks “does this work?”, against deduction, which asks “what has to be true for this to be correct?”. I still think the same, but today I'd put it differently. They aren't rival questions. They're the two halves of the pattern Hughes described almost forty years ago.

Vibecoding is the generate part. A well-made spec—types, properties, proofs—is the prune part. What's being argued today as “vibecoding versus spec-driven” is really people using only one half. Some generate without pruning and pile up regressions; others try to build from a prose blueprint and throw away the advantage of generation being cheap.

In the end, dos and dos' are the same value. What changes is where the confidence comes from. In the constructed two, correctness comes by construction, because there's no way S (S Z) could be anything else. In the found two, correctness comes entirely from the filter, and head . tail . tail $ nats is two because you know exactly what you're observing.

Programming with LLMs is programming by finding. And if you're going to program by finding, the question that matters is no longer how good your generator is. It's how good your filter is.


References

  • Hughes, J. (1989). Why Functional Programming Matters. The Computer Journal, 32(2). PDF
  • Wadler, P. (1985). How to Replace Failure by a List of Successes. FPCA 1985, LNCS 201. DOI
  • Meijer, E., Fokkinga, M. & Paterson, R. (1991). Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire. FPCA 1991. PDF
  • Jacobs, B. & Rutten, J. (1997). A Tutorial on (Co)Algebras and (Co)Induction. EATCS Bulletin, 62. PDF
  • Turner, D. A. (2004). Total Functional Programming. Journal of Universal Computer Science, 10(7). Article
  • Gibbons, J. & Hutton, G. (2005). Proof Methods for Corecursive Programs. Fundamenta Informaticae, 66(4).
  • Erwig, M. & Kollmansberger, S. (2006). Probabilistic Functional Programming in Haskell. Journal of Functional Programming, 16(1).
  • Goodman, N. D. & Tenenbaum, J. B. Probabilistic Models of Cognition. Online book
  • Wirth, N. (1971). Program Development by Stepwise Refinement. Communications of the ACM, 14(4). DOI
  • Morgan, C. (1994). Programming from Specifications (2nd ed.). Prentice Hall. Freely available on the author's website.
  • Back, R.-J. & von Wright, J. (1998). Refinement Calculus: A Systematic Introduction. Springer. DOI
  • Claessen, K. & Hughes, J. (2000). QuickCheck: A Lightweight Tool for Random Testing of Haskell Programs. ICFP 2000. DOI
  • Rutten, J. (2000). Universal Coalgebra: A Theory of Systems. Theoretical Computer Science, 249(1). DOI
  • Laplace, P.-S. (1814). Essai philosophique sur les probabilités.
  • Einstein, A. (1905). Zur Elektrodynamik bewegter Körper. Annalen der Physik, 17. DOI
  • Heisenberg, W. (1969). Der Teil und das Ganze (in Spanish, La parte y el todo). The chapter on the 1926 conversation with Einstein.
  • Noether, E. (1918). Invariante Variationsprobleme. Nachrichten von der Gesellschaft der Wissenschaften zu Göttingen.
  • Jaynes, E. T. (1957). Information Theory and Statistical Mechanics. Physical Review, 106(4). DOI
The code

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

Ragnagrok/building-or-pruning-the-infinite
Support the blog

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