---
title: Calculus of Compositional Copatterns
url: https://www.emergentmind.com/topics/calculus-of-compositional-copatterns
type: topic
---

# Calculus of Compositional Copatterns

Searching arXiv for the cited copattern papers to ground the article.
I’ll look up the arXiv entries for the two papers to anchor the summary in the current record.
Searching arXiv: 1406.2059 and 2508.12427.
The calculus of compositional copatterns denotes a line of work in which copatterns are treated not merely as a notation for codata, but as a disciplined foundation for programming and reasoning about context-sensitive behavior. In one formulation, copatterns are refactored into a formal calculus with explicit responses, nested options, and delimited questions, yielding a semantics presented in CPS, as an abstract machine, and as a small-step reduction system [2508.12427]. In another, earlier formulation, the same compositional idea appears as a concrete Agda development for coinductive normalization by evaluation in the sized delay monad, where coinductive objects are defined by copattern clauses for their observations and then composed monadically [1406.2059].

## 1. Copatterns as context-sensitive observations

Copatterns are the dual of ordinary patterns. Pattern matching inspects data produced by a term, whereas copattern matching describes how a value responds to the observations imposed by its context. In the 2025 calculus, the relevant observations are application to arguments, $M~N$, and projection by indices, $M~X$; a copattern is a sequence of such interrogations that leads to a result [2508.12427]. The paper explicitly characterizes copatterns as matching on the *context of use* of a value rather than on the shape of input data.

The Agda case study realizes the same idea in a coinductive setting. There, coinductive objects are records whose behavior is given by equations for observable fields instead of by constructors. The central example is the coinductive record
```agda
record ∞Delay (i : Size) (A : Set) : Set where
  coinductive
  field
    force : {j : Size< i} → Delay j A
```
An element of `∞Delay` is therefore determined by what happens when it is `force`d. The canonical divergent computation
```agda
never : ∀ {i A} → ∞Delay i A
force (never {i}) {j} = later (never {j})
```
is defined by a copattern clause on `force`, and the same style is used for `beta` and `eta` in the normalizer [1406.2059].

Across both formulations, the common principle is that coinductive or object-like behavior is specified through observable eliminations. The 2014 development presents coinductive objects as observation transformers whose definitions unfold stepwise through `force`, while the 2025 development generalizes that perspective to a calculus in which the calling context itself becomes an explicit semantic object [1406.2059] [2508.12427].

## 2. From monolithic clauses to compositional copatterns

The 2025 paper begins from a calculus of **monolithic copatterns**. Its syntax includes terms, options, and copatterns:
$$
\begin{aligned}
\mathit{Term} \ni M, N &::=&~ x \mid M ~ N  \mid M ~ X  \mid M .  \mid \lambda \{\many{O}\} \\
\mathit{Option} \ni O &::=&~ L \to M \\
\mathit{Copat} \ni L &::=&~ \varepsilon  \mid x ~ L  \mid X ~ L
\end{aligned}
$$
A copattern lambda $\lambda\{L_i \to M_i\}$ is evaluated against a context and selects the first matching clause. Its equational basis consists of open recursion,
$$
(\delta)\quad M. = M ~ M,
$$
and copattern resolution,
$$
(\beta)\quad C[\lambda\{\many[1 \leq i \leq n]{L_i \to M_i}\}] = M_j\vec{\sigma},
$$
subject to the matching condition stated in the paper [2508.12427].

The paper then isolates the limitations of this monolithic form: non-compositional failure handling, absence of nested option structure, and limited modularity for vertical composition. These limitations motivate the **calculus of compositional copatterns**, in which matching behavior is decomposed into smaller units that can be nested and chained via failure continuations [2508.12427].

The resulting syntax is:
$$
\begin{aligned}
\mathit{Response} \ni R &::= q \mid \varepsilon \mid M \ans R \\
\mathit{Term} \ni M, N &::= x \mid M~N \mid M~X \mid M. \mid \Raise \mid O \ask M \mid \ans q \to R \\
\mathit{Option} \ni O &::= x \to O \mid X \to O \mid \ask x \to M
\end{aligned}
$$
Here, $O \ask M$ means “try option $O$ first; if it cannot handle the current context, fall through to $M$.” The forms $x \to O$, $X \to O$, and $\ask x \to M$ decompose copattern matching into argument consumption, index checking, and successful completion, respectively [2508.12427].

The paper also gives explicit translations between monolithic and compositional syntax. In particular,
$$
O \ask M = \lambda\{O \mid \varepsilon \to M\},
$$
and nested options can encode a list of monolithic clauses. Conversely, monolithic copattern lambdas can be translated into iterated uses of $O \ask M$ ending in $\Raise$. The paper therefore describes the compositional calculus as a **conservative extension** of the monolithic one [2508.12427].

## 3. Semantic architecture: CPS, abstract machines, and small-step reduction

A central feature of the compositional calculus is that it is presented through multiple, corresponding semantic artifacts. For the monolithic calculus, the paper derives a small-step operational semantics, then an abstract machine, then a CPS transformation using Danvy’s syntactic and functional correspondences. Within CPS, the semantics is refactored to obtain the more general compositional calculus; then the process is reversed to derive an abstract machine and a small-step semantics for the new language [2508.12427].

For monolithic copatterns, evaluation contexts are represented as questions:
$$
\mathit{Cont} \ni K ::= \varepsilon \mid N ~ K \mid X ~ K.
$$
The abstract machine uses refocusing states $\cut{M}{K}$ and copattern-matching states $\langle L \mid K \mid M \mid \vec{O} \mid K \rangle$, with steps such as
$$
\cut{M~N}{K} \mapsto \cut{M}{N~K}, \qquad
\cut{M~X}{K} \mapsto \cut{M}{X~K},
$$
and
$$
\cut{M.}{K} \mapsto \cut{M}{M~K}.
$$
Copattern matching consumes the question incrementally until either a clause succeeds or control falls through to the remaining options [2508.12427].

The refactoring to compositional copatterns introduces **responses** and **answer abstractions**:
$$
\mathit{Response} \ni R ::= q \mid \varepsilon \mid M \ans R, \qquad
\mathit{Term} \ni M ::= \dots \mid \ans q \to R.
$$
Operationally, $M \ans R$ delimits a question, and the constant
$$
\Raise \equiv \ans q \to q
$$
represents “raise the current question as an unhandled error.” The paper identifies this structure as a form of **call-by-name delimited control**; nested options and failure handlers thereby acquire a direct control-theoretic interpretation [2508.12427].

The final CPS transformation for the compositional calculus makes this explicit. For example,
$$
\den{\Raise} = \lambda k.~\lambda s.~s~k, \qquad
\den{O \ask M} = \lambda k.~\den{O}~\den{M}~k,
$$
while options propagate failure by reconstructing the continuation shape. The return journey yields an abstract machine with terms, continuations, meta-continuations, and environments, as well as a direct small-step semantics with evaluation contexts
$$
\mathit{EvalCxt} \ni E ::= \square \mid E~N \mid E~X
$$
and delimiter contexts
$$
\mathit{DelimCxt} \ni D ::= \square \mid M \ans D.
$$
The paper states semantic equivalence across the small-step semantics, abstract machine, and CPS account for both the monolithic and compositional calculi, and uses that equivalence to argue that the added expressiveness remains controlled [2508.12427].

## 4. The Agda case study: a concrete calculus in the sized delay monad

The 2014 paper does not present a separate formal calculus of compositional copatterns. Instead, it gives what it explicitly describes as a very concrete, worked-out *calculus* for programming with copatterns in a compositional style, in the setting of coinductive normalization by evaluation via the sized delay monad [1406.2059].

The delay monad is split into an inductive layer and a coinductive layer:
```agda
mutual
  data Delay (i : Size) (A : Set) : Set where
    now   : A → Delay i A
    later : ∞Delay i A → Delay i A

  record ∞Delay (i : Size) (A : Set) : Set where
    coinductive
    field
      force : {j : Size< i} → Delay j A
```
`now a` makes a result immediately available, while `later a∞` delays the computation by one observable step. A value of type `Delay ∞ A` may therefore contain infinitely many `later`s and model nontermination [1406.2059].

At each size, `Delay i` is given a monad structure. Return is `now`, and bind is defined mutually with its coinductive part:
```agda
module Bind where
  mutual
    _>>=_ : ∀ {i A B} →
             Delay i A → (A → Delay i B) →
             Delay i B
    now a     >>= f = f a
    later a∞  >>= f = later (a∞ ∞>>= f)

    _∞>>=_ : ∀ {i A B} →
             ∞Delay i A → (A → Delay i B) →
             ∞Delay i B
    force (a∞ ∞>>= f) = force a∞ >>= f
```
This is a paradigmatic compositional copattern definition: the coinductive part `_∞>>=_` is defined by a `force` clause, while the inductive layer guarantees that corecursive unfolding remains guarded [1406.2059].

The main coinductive components of the normalizer are the evaluator, the application function, and the delayed $\beta$-step:
```agda
eval  : ∀ {i Γ Δ b} →
        Tm Γ b → Env Δ Γ → Delay i (Val Δ b)
apply : ∀ {i Δ a b} →
        Val Δ (a ⇒ b) → Val Δ a →
        Delay i (Val Δ b)
beta  : ∀ {i Γ Δ a b} →
        Tm (Γ , a) b → Env Δ Γ → Val Δ a →
        ∞Delay i (Val Δ b)

eval (var x) ρ       = now (lookup x ρ)
eval (abs t) ρ       = now (lam t ρ)
eval (app t u) ρ     =
  eval t ρ >>= λ f →
  eval u ρ >>= λ v →
  apply f v

apply (ne w)      v  = now (ne (app w v))
apply (lam t ρ)   v  = later (beta t ρ v)
force (beta t ρ v)   = eval t (ρ , v)
```
The reifier is defined in a parallel style, with delayed $\eta$-expansion captured by:
```agda
eta : ∀ {i Γ a b} →
      Val Γ (a ⇒ b) →
      ∞Delay i (Nf (Γ , a) b)

force (eta v) =
  readback =<< apply (weakVal v) (ne (var zero))
```
The normalizer itself is then the composition
```agda
nf : ∀ {Γ a} (t : Tm Γ a) →
     Delay ∞ (Nf Γ a)
nf {Γ} t = eval t (ide Γ) >>= readback
```
The paper’s central methodological point is that independently defined coinductive components such as `beta`, `eta`, and `_∞>>=_` can be combined in a modular way, with copattern clauses specifying observable steps and monadic combinators handling composition [1406.2059].

## 5. Productivity, bisimilarity, and a posteriori totality

The Agda development separates productivity from termination. Productivity is enforced by **sized types**: if
```agda
force : {j : Size< i} → Delay j A
```
then every observation decreases the size index. The paper states that “The use of copatterns reduces productivity checking to termination checking,” because Agda checks that the recursive call receives a strictly smaller size parameter. This is applied directly to `never`, `beta`, and `eta`, whose `force` clauses expose one step of the delayed computation at smaller depth [1406.2059].

The monad laws are not proved by definitional equality, but **up to strong bisimilarity**. The paper defines a coinductive bisimilarity relation
```agda
mutual
  data _∼_ {i}{A} (a? b? : Delay ∞ A) : Set where
    ∼now   : ∀ a → now a ∼ now a
    ∼later : ∀ {a∞ b∞} (eq : a∞ ∞∼⟨ i ⟩∼ b∞) →
             later a∞ ∼ later b∞

  record _∞∼⟨_⟩∼_ {A} (a∞ : ∞Delay ∞ A) i (b∞ : ∞Delay ∞ A) : Set where
    coinductive
    field
      ∼force : {j : Size< i} → force a∞ ∼⟨ j ⟩∼ force b∞
```
and uses copatterns again to specify how equality unfolds through `force` [1406.2059].

Termination is then proved *a posteriori* by logical relations. The strong computability predicates on values and delayed computations are:
```agda
V⟦_⟧_ : ∀ {Γ} (a : Ty) → Val Γ a → Set
C⟦_⟧_ : ∀ {Γ} (a : Ty) → Delay ∞ (Val Γ a) → Set

V⟦ ★ ⟧ (ne w) =
  nereadback w ↓
V⟦ a ⇒ b ⟧ f =
  ∀ {Δ} (η : Δ ≤ Γ) (u : Val Δ a) →
    V⟦ a ⟧ u →
    C⟦ b ⟧ (apply (val≤ η f) u)
C⟦ a ⟧ v? =
  ∃ λ v → v? ↓ v × V⟦ a ⟧ v
```
with a parallel predicate on environments:
```agda
E⟦ Γ ⟧ ρ : Set
E⟦ ε ⟧ ε              = ⊤
E⟦ Γ , a ⟧ (ρ , v)    = E⟦ Γ ⟧ ρ × V⟦ a ⟧ v
```
The paper proves weakening lemmas, soundness of delayed $\beta$-expansion, the fundamental theorem `term`, and mutual `reify`/`reflect` lemmas for readback. The final result is:
```agda
normalize : ∀ Γ a (t : Tm Γ a) →
             ∃ λ n → nf t ↓ n
```
Thus the composed program `nf` is defined coinductively and may in principle diverge, but for simply typed $\lambda$-terms it always converges. This is the paper’s strongest evidence that copattern-based, monadically composed coinductive programs can remain total when supported by an appropriate semantic argument [1406.2059].

## 6. Examples, connections, and open directions

The 2025 paper illustrates the monolithic calculus with a counting stream:
$$
\mathit{count} = \lambda \begin{aligned}[t]
\{& \mathit{self}~\mathit{From}~x~\mathit{Head} \to x \\
\mid& \mathit{self}~\mathit{From}~x~\mathit{Tail} \to \mathit{self}.\mathit{From}(\mathit{succ}~x) \}
\end{aligned}
$$
The reduction of the third element proceeds by alternating the open-recursion rule $(\delta)$ with copattern resolution $(\beta)$ until the result $\mathit{succ}(\mathit{succ}~0)$ is obtained [2508.12427]. It also presents Scheme macro examples for object-like programming, including an arithmetic interpreter `arith`, a vertical composition `arith-ext`, and environment-carrying objects such as `with-env` and `alg`. These examples are used to explain how $O \ask M$ expresses vertical composition by “try this behavior first; otherwise fall through” [2508.12427].

The 2014 case study connects the same compositional perspective to normalization by evaluation. There, `beta` embodies delayed $\beta$-reduction, `eta` embodies delayed $\eta$-expansion, and `_>>=_` provides the monadic composition law that combines evaluator and reifier into a single coinductive normalizer [1406.2059]. This suggests a methodological continuity: the later formal calculus makes explicit, in control-theoretic syntax and semantics, a style of modular copattern programming that the earlier Agda development already used in a typed and coinductive setting.

Both papers situate copatterns in broader theoretical contexts. The 2025 paper links compositional copatterns to codata, coalgebraic models, object-oriented interfaces, delimited control, and algebraic effects; it treats the calling context as a continuation and nested options as first-class handlers in a call-by-name setting [2508.12427]. The 2014 paper places its approach alongside Capretta’s delay/partiality monad, Danielsson’s partiality monad, copattern theory by Abel et al., and guarded definitions in Coq and earlier Agda, while contrasting sized types with guarded recursion via later modalities [1406.2059].

The limitations are also explicit. In the Agda work, copatterns and sized types were experimental features, and the “calculus” remained concrete, embedded in Agda rather than developed as a separate formal system [1406.2059]. The later paper addresses precisely that gap by deriving a formal calculus of compositional copatterns with syntax and semantics at several levels of abstraction [2508.12427]. A plausible implication is that the two papers collectively define a trajectory for the subject: from a proof-of-concept of compositional copattern programming in a dependently typed implementation to a direct semantic theory in which composition, failure, and control are themselves first-class components of the calculus.

Source: https://www.emergentmind.com/topics/calculus-of-compositional-copatterns