← All articles

The Art of Building with Smart Pieces: Combinators in the Age of LLMs

15 min readsoftware-design-patternssoftware-architecturefunctional-programmingsoftware-engineeringlibrary-design

Machine-translated from Spanish. Read the original

ByFederico Sawady O'ConnorRagnagrok Academy

In our industry we tend to argue about languages, frameworks and architectures, but there's a technique born at the heart of functional programming that, almost without us noticing, has become one of the most elegant tools for designing software interfaces. I'm talking about combinators.

If you've ever felt that programming is a lot like playing with Lego, it's because you were intuitively using the power of composition. What gets interesting is what happens when we take that idea to the extreme and use it to get language models to generate better code for us.

What exactly is a combinator?

The term may sound like category theory or abstract algebra, but in practice it's much simpler. A combinator is a function that takes simple pieces and combines them into a more complex piece, without adding any external “magic” logic.

The key is that the new piece has the same shape as the originals. That lets you keep combining it with others of the same type, without friction, forming a tree that grows naturally.

Picture two blocks:

  • a function that knows how to read a file,
  • another that knows how to filter text.

A combinator is the tool that glues those two blocks together and returns a third one — a reader-filter — that you can keep combining as if it were a primitive. In essence, combinators let you define a small language (an embedded DSL) inside your own code, where the rules for how pieces fit together are clear and strict.

The idea is old. It comes from Schönfinkel and Curry's combinatory logic in the 1920s, and it landed in modern programming through Haskell, Scala, OCaml and friends. But only now, with LLMs changing how we write software, is it showing a side few people saw coming.

Throughout the article I'll use TypeScript for the examples. It's a language almost all of us can read, and its type system is expressive enough to show the heart of the matter, which is how types guarantee that the pieces fit.

Example 1. Parsers, the “Hello World” of combinators

This is the classic use case. Instead of writing a giant, unreadable regular expression to parse something, you build the parser by combining tiny pieces. Let's start with the type:

// A parser is a function that takes an input (string)
// and, if it succeeds, returns a value of type T plus whatever was left unconsumed.
type Parser<T> =
  (input: string) =>
    | { ok: true; value: T; rest: string }
    | { ok: false };

That Parser<T> is the common "shape." Everything we define will go in and come out with that same shape. That's the rule of the game.

Primitives (basic parsers):

const char = (c: string): Parser<string> =>
  (input) =>
    input[0] === c
      ? { ok: true, value: c, rest: input.slice(1) }
      : { ok: false };

const digit: Parser<number> = (input) => {
  const ch = input[0];
  return ch && /[0-9]/.test(ch)
    ? { ok: true, value: Number(ch), rest: input.slice(1) }
    : { ok: false };
};

Combinators (they take parsers and return parsers):

// "This AND THEN that": combines two parsers in sequence.
const and = <A, B>(pa: Parser<A>, pb: Parser<B>): Parser<[A, B]> =>
  (input) => {
    const r1 = pa(input);
    if (!r1.ok) return { ok: false };
    const r2 = pb(r1.rest);
    if (!r2.ok) return { ok: false };
    return { ok: true, value: [r1.value, r2.value], rest: r2.rest };
  };

// "This OR that": tries the first one, and if it fails, the second.
const or = <A>(pa: Parser<A>, pb: Parser<A>): Parser<A> =>
  (input) => {
    const r1 = pa(input);
    return r1.ok ? r1 : pb(input);
  };

// "Repeat zero or more times": applies the parser until it fails.
const many = <A>(pa: Parser<A>): Parser<A[]> =>
  (input) => {
    const out: A[] = [];
    let rest = input;
    while (true) {
      const r = pa(rest);
      if (!r.ok) break;
      out.push(r.value);
      rest = r.rest;
    }
    return { ok: true, value: out, rest };
  };

Look at the signatures. This is the important part:

  • and takes Parser<A> and Parser<B> and returns Parser<[A, B]>.
  • or takes two Parser<A> and returns Parser<A>.
  • many takes Parser<A> and returns Parser<A[]>.

The types tell you exactly how the pieces fit. If you try and(digit, "hola"), the compiler stops you, because "hola" is not a Parser<B> for any B. If you try or(digit, char('a')), it stops you too, since one is Parser<number> and the other Parser<string>, and or requires both to return the same type.

Now composing is trivial. A parser for “one or more digits as a number”:

const integer: Parser<number> = (input) => {
  const r = and(digit, many(digit))(input);
  if (!r.ok) return { ok: false };
  const [head, tail] = r.value;
  return { ok: true, value: Number([head, ...tail].join("")), rest: r.rest };
};

From here, a parser for JSON, for dates, for a mini language, whatever you want, falls out of composition. The real TypeScript libraries that take this to production are Parsimmon, Arcsecond and parjs; in Haskell, Parsec and megaparsec are the reference. The foundational paper is Hutton and Meijer's Monadic Parser Combinators (1996), which shows how parsers form a monad.

Correction (November 2, 2026). This many hangs if the inner parser can succeed without consuming anything, and many(many(char('a'))), for example, never ends, because the inner many always succeeds, even when there's no a. Parsec detects that case and reports it as an error; a minimal version like this one doesn't. Stopping the loop when the parser made no progress (r.rest === rest) is enough. I found it while turning the article into code that runs, and the repo has the four examples, their laws checked, and a test that shows the loop.

One real case is the team at Mercury, who used Parsimmon to build a date picker that understands inputs like “last 3 months” or “since March.” That's where you see how, where a regex becomes impenetrable, combinators offer something readable, testable and extensible.

Example 2. Queries without string concatenation

The same pattern applied to databases. Let's define a type for predicates over a table:

// A predicate is a WHERE fragment typed by the table T.
type Predicate<T> = {
  sql: string;
  params: unknown[];
  // The `_phantom` parameter isn't used at runtime; it lets TypeScript
  // know which table this predicate applies to.
  readonly _phantom?: (t: T) => void;
};

type User = { id: number; age: number; active: boolean };

Primitives over User:

const esAdulto: Predicate<User> = {
  sql: "age >= ?",
  params: [18],
};

const tieneSubActiva: Predicate<User> = {
  sql: "active = ?",
  params: [true],
};

Combinators that compose predicates:

const and = <T>(p1: Predicate<T>, p2: Predicate<T>): Predicate<T> => ({
  sql: `(${p1.sql}) AND (${p2.sql})`,
  params: [...p1.params, ...p2.params],
});

const not = <T>(p: Predicate<T>): Predicate<T> => ({
  sql: `NOT (${p.sql})`,
  params: p.params,
});

And the composition:

const usuariosVip: Predicate<User> = and(esAdulto, tieneSubActiva);
// usuariosVip.sql    -> "(age >= ?) AND (active = ?)"
// usuariosVip.params -> [18, true]

The _phantom parameter is what's known as a phantom type, which doesn't exist at runtime but tells TypeScript that esAdulto (Spanish for isAdult) is only valid over User. If you have another table type Post = ..., trying and(esAdulto, predicadoSobrePost) (a predicate over Post) is a compile error. SQL stops being a loose string and becomes a typed, composable, reusable value.

Correction (November 2, 2026). This holds when the rows of the two tables have different shapes. TypeScript compares types by structure, so two tables whose rows have the same shape mix without error. Telling them apart needs a mark of each table's own, such as a field readonly __table?: "users". The repo has the case that compiles and shouldn't.

This isn't theoretical. Libraries like Drizzle in TypeScript, Slick in Scala, Diesel in Rust or Esqueleto in Haskell apply exactly this pattern. Massive refactors become almost trivial, and “SQL as a string” stops being the number-one source of runtime bugs.

Example 3. Graphical interfaces as combinators

React, SwiftUI and Elm lean heavily on this idea. In React, a higher-order component (HOC) is literally a combinator over components:

import { ComponentType } from "react";

// A combinator that wraps any component and adds
// a spinner while `isLoading` is true.
const withLoading = <P extends object>(
  Component: ComponentType<P>
): ComponentType<P & { isLoading: boolean }> =>
  ({ isLoading, ...props }) =>
    isLoading
      ? <Spinner />
      : <Component {...(props as P)} />;

The signature speaks for itself, and it says that withLoading takes a component with props P and returns a component with props P & { isLoading: boolean }. The shape is preserved, the types get richer. And since the result is once again a component, you can wrap it again:

const withAuth = <P extends object>(
  Component: ComponentType<P>
): ComponentType<P> => /* ... */;

const PerfilProtegido = withAuth(withLoading(Perfil));

For a complex UI, it's far more manageable to compose a tree with clear nesting rules than to write loose HTML/CSS and pray. And for an LLM, this structure is much easier to generate correctly.

Example 4. Agent orchestration and AI pipelines

This is where the pattern gets really interesting. Let's model interactions with LLMs as an algebra. The basic piece:

// An AI step takes an input and asynchronously produces an output.
// That's the "shape" common to the whole system.
type Step<I, O> = (input: I) => Promise<O>;

Primitives:

const prompt =
  (template: string): Step<Record<string, string>, string> =>
  async (vars) => {
    const filled = fillTemplate(template, vars);
    return await llm.complete(filled);
  };

const extractJSON = <T>(schema: Schema<T>): Step<string, T> =>
  async (text) => parseAndValidate(text, schema);

Combinators:

// Chains two steps: the output of the first feeds the second.
const chain = <A, B, C>(s1: Step<A, B>, s2: Step<B, C>): Step<A, C> =>
  async (input) => s2(await s1(input));

// Runs two steps in parallel over the same input.
const parallel = <I, A, B>(
  s1: Step<I, A>,
  s2: Step<I, B>
): Step<I, [A, B]> =>
  async (input) => Promise.all([s1(input), s2(input)]);

// Retries until the verifier accepts the result.
const retryUntil = <I, O>(
  s: Step<I, O>,
  verify: (out: O) => boolean,
  maxAttempts = 3
): Step<I, O> =>
  async (input) => {
    for (let i = 0; i < maxAttempts; i++) {
      const out = await s(input);
      if (verify(out)) return out;
    }
    throw new Error("Verification failed after all attempts");
  };

Once again, look at the signatures. chain requires the output of s1 to match the input of s2 exactly. If you chain a step that returns string with one that expects User, the compiler stops you. You describe the processing graph; the types guarantee the data flows correctly:

const analizarReseña: Step<{ texto: string }, { sentimiento: string; resumen: string }> =
  chain(
    prompt("Analyze this review: {texto}. Return JSON with sentimiento and resumen."),
    extractJSON<{ sentimiento: string; resumen: string }>(reviewSchema)
  );

Once you have that vocabulary, a complex agent stops being a tangled script of API calls and becomes a compositional expression that reads almost like pseudocode. Frameworks like LangChain, LangGraph and especially DSPy are exploring this territory. DSPy treats prompts as optimizable modules and composes pipelines as typed programs.

Type systems as an automatic instruction manual

Types work like the studs on Lego bricks, which keep you from trying to join pieces that don't fit. In every one of the examples we saw the same thing:

  • Parser<T> composes with other Parser<U> following strict rules.
  • Predicate<User> doesn't mix with Predicate<Post> (if their rows have different shapes).
  • Step<A, B> only chains with Step<B, C>.

The compiler stops you before anything runs. It's not a complete formal guarantee, but it filters out an enormous number of errors that in other paradigms only show up in production. In languages with more expressive type systems — Haskell, Scala, Rust — this pattern goes even further.

Combinators and LLMs, programming for language models

Today the programmer is no longer the only one writing code. Claude, GPT, Gemini and friends are in the copilot's seat. And while they're surprisingly capable, they still struggle with complex logic and produce “spaghetti” code that's hard to validate. This is where combinators become an especially useful bridge.

Constraining the search space. Instead of asking the model to write 100 lines of raw code, we ask it to combine primitives from a well-designed library. It's far easier for an LLM to choose among 5 valid combinators — chain, parallel, retryUntil...— than to invent logic from scratch. Less surface for error, more predictability.

Immediate validation. If the model puts together an invalid combination, the type system fails. That error is a precise signal, not noise, so it can be fed back into the model in a deterministic self-correction loop. The retryUntil from the previous example is only half of that loop, because it retries until the verifier accepts, but it calls again with the same input and doesn't pass the error to the model.

Hierarchical structure. Combinators force trees, not disorderly chains of tokens. And it turns out LLMs are very good at generating nested structures when the grammar is well defined.

That last point connects with a very active line of research, the one on constrained decoding or grammar-constrained decoding. The idea is to restrict, at inference time, which tokens the model can emit at each step so the output respects a formal grammar. Work like Geng et al. (2023) on grammar-constrained decoding and engines like XGrammar show that you can force an LLM to generate exclusively valid JSON, well-formed SQL, or any DSL defined by a context-free grammar, without sacrificing much performance.

If your combinator library has a formal grammar — which is exactly what they have by construction — you can use constrained decoding techniques so that the model literally cannot write malformed code. The grammar covers syntax and not types, so immediate validation is still needed. The intersection between classic functional programming and LLM generation is one of the most fertile spaces right now.

Correction (November 25, 2026). The first version said retryUntil already does that self-correction loop, and that with constrained decoding the model can't write code that doesn't compile. Neither holds, because retryUntil repeats the same input without passing the error to the model, and a grammar guarantees syntax but not types. The section's idea still stands, but it takes both layers, the grammar and the type check. I found it in a review of the series, and the repo has the retryUntil and rejected files that are syntactically valid and only fail when types are checked. It also dated the work by Geng et al. to 2024, but it's from 2023 and was published at EMNLP.

Algebras and laws, the guide to a reasonable AI

Very often, a set of combinators defines what's called an algebra. That means the combinations obey mathematical laws, such as associativity (it doesn't matter how you group the pieces as long as the order stays the same), the existence of an identity element (a neutral piece) or distributivity over certain operations.

For example, with the chain we defined above:

chain(chain(a, b), c)  ≡  chain(a, chain(b, c))

The two expressions are interchangeable. And that enables three things.

Optimization. The system (or the model, guided by rules) can refactor to improve performance without breaking the logic.

Symbolic reasoning. We can guide the model to apply transformations that respect the laws of the algebra. This comes close to what tools like QuickCheck already do in testing, where properties are verified instead of individual cases.

Fewer hallucinations. By limiting the model's options to “combine these N functions” instead of “write anything,” we drastically shrink the space where it can hallucinate. The model stops being a free-form generator and becomes an assembler of valid pieces.

A note on costs

I don't want to paint this approach as free. Combinators have their dark side. The learning curve is real (especially once monads or other similar algebraic structures show up), error messages in heavily typed libraries can be indecipherable — ask anyone who's wrestled with types in Parsec or with HKTs in Scala — , and there's a non-negligible runtime cost compared to equivalent imperative code. For small problems it's sometimes overkill. But in domains where correctness and composability matter more than the shortcut — parsers, queries, AI pipelines, DSLs — it pays for itself.

Back to the roots to build the future

There's something almost ironic in the fact that, to get the most out of the newest technology around, the best tools come from the oldest, most solid theoretical computer science. Combinators aren't just an elegant functional programming technique; they're one of the most natural interfaces for humans and models to collaborate on building complex, safe and predictable software.

Designing a library today is no longer just about the human developer. It's about designing a language of combinable blocks that a model can understand, respect and amplify. And that, coming from an idea from the 1920s, is quite a nice twist.

References

The code

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

Ragnagrok/the-art-of-building-with-smart-pieces
Support the blog

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