---
title: 'Cost-Free Types: Theory and Applications'
url: https://www.emergentmind.com/topics/cost-free-types
type: topic
---

# Cost-Free Types: Theory and Applications

Cost-free types designate a family of techniques in which type information is intended to impose little or no additional burden—at run time, in proof engineering, or in resource analysis—while still providing stronger specifications, error detection, or certified bounds. In the literature, the phrase appears in several distinct but related senses: transient gradual typing whose checks are “almost free” on an optimizing VM, zero-cost coercions and reuse in dependent type theory, cost-free typings inside Automatic Amortized Resource Analysis (AARA), fixtype disciplines that remove type hypotheses from ACL2 theorems, and dependent type theories in which cost bounds are carried intrinsically by types themselves [1807.00661], [1803.08150], [2509.22982], [1509.06079], [2601.10772].

## 1. Multiple technical meanings of “cost-free”

In gradual typing, the central question is whether adding type annotations slows programs down. “Transient Typechecks are (Almost) Free” studies transient gradual typing in Grace on Graal/Truffle and argues that standard JIT optimizations can reduce the overhead of transient checks to near zero, so programmers can add types “without affecting their programs’ performance” on realistic workloads [1807.00661]. In dependently typed programming, “Generic Zero-Cost Reuse for Dependent Types” uses identity coercions whose erased term is definitionally equal to the untyped identity `λx. x`, so conversions between indexed and unindexed views incur no runtime penalty [1803.08150].

In AARA, cost-free types have a different role. They are typings in which ticks are ignored, so no potential is consumed and annotations describe only potential-preserving transfer from inputs to outputs. They are used compositionally, especially for resource-polymorphic recursion, and recent work represents them with a linear map that can stand for infinitely many cost-free types [2509.22982]. In ACL2, “Fix Your Types” uses a fixtype discipline so that types help “catch programming errors and then get out of the way of theorem proving,” specifically by avoiding type hypotheses and their proof-search costs [1509.06079].

A further line of work internalizes cost directly into type theory. Resource-Bounded Martin-Löf Type Theory extends MLTT with dependent types, a resource-indexed universe hierarchy \(U_r\), and a graded modality \(\Box_r\), so that typing derivations certify upper bounds on operational cost [2601.10772]. Cost-Aware Type Theory distinguishes ordinary extensional membership from cost-bounded membership and introduces the dependent function type “funtime” \(\arrtimev{\isOf{a}{A}{B}{P}\), making cost a primitive semantic notion rather than an external analysis [2011.03660]. This suggests that “cost-free types” is best understood as a unifying theme rather than a single formal mechanism.

## 2. Near-zero runtime overhead in gradual typing

Transient gradual typing enforces types by explicit use-site checks rather than proxies. Values are never wrapped or cast; instead, the language inserts tests of the form
\[
\texttt{check}(v, T)
\]
which raise a type error if \(v \not\in \llbracket T \rrbracket\). Typed variable reads, method arguments, returns, and typed collection operations therefore generate runtime tests under a naive compilation strategy [1807.00661].

That naive strategy leads to the expected linear slowdown: if \(N(n)\) is the number of type-check operations executed on input size \(n\), then the runtime can be modeled as
\[
T_{\text{typed}(n) = T_{\text{untyped}(n) + c \cdot N(n),
\]
and in many real programs \(N(n)\) scales linearly with the number of hot-path operations, yielding a roughly constant-factor slowdown [1807.00661]. The paper’s contribution is to show that this theoretical picture does not determine optimized execution on Graal/Truffle.

The implementation context is Grace with transient-type semantics on the Moth interpreter/JIT, using an AST interpreter with node rewriting and partial evaluation. Type checks are represented directly as AST nodes. Graal/Truffle then applies standard optimizations: inline caching and type feedback turn stable checks into constant conditions; specialization and constant propagation eliminate redundant checks; common subexpression elimination removes repeated predicates; loop-invariant code motion hoists stable checks out of loops; escape analysis removes intermediates; and aggressive inlining exposes method-boundary checks to local optimization [1807.00661].

The empirical outcome is the paper’s “almost free” claim. For most benchmarks, the transiently typed version lies very close to untyped performance on a runtime-factor axis normalized to untyped Moth; some benchmarks are slightly below 1.0, a few show overhead up to about \(1.1\text{–}1.2\times\), and some configurations reach \(1.5\) or above in whiskers. The reported flattening of the overhead curve as type coverage increases is especially important: large increases in type coverage do not produce proportional increases in runtime [1807.00661]. The caveats are equally explicit. Highly polymorphic code, unstable data structures, reflection, dynamic code loading, limited profiling or warm-up, and more complex type-system features can prevent elimination of transient checks and leave residual overhead on hot paths [1807.00661].

## 3. Zero-cost coercions and reuse in dependent types

In Curry-style dependent type theory, cost-free typing is often literal runtime identity. “Generic Zero-Cost Reuse for Dependent Types” exploits the fact that the same untyped term may be classified as both non-indexed and indexed datatypes. The paper’s central construction is the dependent identity type
\[
\text{IdDep}\ A\ B \triangleq \Pi a : A.\ \Sigma (B\ a)\ (\lambda b.\ b \simeq a),
\]
together with its eliminator
\[
\text{elimIdDep} : \forall A : \star.\ \forall B : A \to \star.\ \text{IdDep}\ A\ B \to \Pi a : A.\ B a.
\]
The eliminator is implemented with Cedille’s `phi` operator so that its erasure is the runtime identity:
\[
|\text{elimIdDep}\ c| = \lambda a.\ a.
\]
A coercion extracted from `IdDep` therefore has the target type but erases to `λa. a`, yielding zero runtime cost [1803.08150].

This framework is used to address reuse between datatypes such as lists and vectors, or raw and typed syntax. Traditional conversions like `List A → Vec A (len xs)` are linear-time traversals in Church-style systems, because the indexed structure must be rebuilt. In CDLE, the conversion can instead be internalized as an identity coercion, provided the underlying erased terms coincide. The paper defines zero-cost conversions between `Vec A n` and `List A`, proves extensional equalities such as `v2l xs ≃ xs` and `l2v xs ≃ xs`, and then constructs `v2l!` and `l2v!` whose erasures are both `λxs. xs` [1803.08150].

The same methodology scales to program reuse. For append, the forgetful conversion from
\[
\text{AppV} = \forall n.\ Vec\ A\ n \to \forall m.\ Vec\ A\ m \to Vec\ A\ (add\ n\ m)
\]
to
\[
\text{AppL} = List\ A \to List\ A \to List\ A
\]
is shown to erase to the identity on the function itself. Generic combinators such as `allArr2arr`, `allPi2pi`, `arr2allArrP`, `ifix2fix`, and `fix2ifix` systematically lift such identity coercions over function spaces and fixpoints, preserving zero-cost behavior throughout [1803.08150].

The approach is nevertheless conditional. The paper notes that zero-cost conversion requires indexed information to reside in erased arguments so that indexed and unindexed representations match after erasure. Forgetful program reuse also becomes problematic when the indexed domain is genuinely restricted, as with `headV : ∀ n. Vec A (suc n) → A`, because there is no corresponding unrestricted `List A` inhabitant at all indices [1803.08150].

## 4. Cost-free types in amortized resource analysis

In AARA, a cost-free type is not a coercion and not a runtime optimization. It is a typing derivation “in which ticks are ignored,” so that annotations describe a potential-preserving transformation from argument potential to result potential. If \(\vec a\) is a costful annotation vector and \(\vec b\) is a cost-free one, then \(\vec a + k \cdot \vec b\) is again a valid costful type for any \(k \ge 0\). Cost-free types therefore encode homogeneous solutions that support tight compositional bounds and resource-polymorphic recursion [2509.22982].

The classical difficulty is inference. Earlier algorithms retyped a function cost-freely at each call site using an excess annotation vector \(\vec b\), and recursive calls required recursively discovering more cost-free types. For polynomial potential, termination was forced by a heuristic: at each iteration the highest-degree annotation in \(\vec b\) is assumed to be zero. Even then, the number of generated constraints can grow exponentially; the paper derives a bound
\[
T(d,c,\ell) \le O\left(d c^{\ell+1} \binom{d+\ell+1}{d}\right)
\]
for synthetic patterns. The heuristic is also not applicable to exponential bounds, where the highest-base coefficient changes under the Stirling recurrence and therefore does not cancel in the required way [2509.22982].

The new approach represents the cost-free behavior of a function with a single linear map
\[
M : (\text{annotation vector on argument}) \longrightarrow (\text{annotation vector on result}).
\]
A function type is annotated as \(#1 \tau \sigma M\), and for every nonnegative annotation vector \(\vec p\), the corresponding cost-free typing is obtained by mapping \(\vec p\) to \(M \cdot \vec p\). One matrix thus stands for infinitely many cost-free types. The paper gives explicit matrices for polynomial and exponential potential, including a polynomial `half` matrix that maps
\[
\begin{bmatrix}
1\\
2\\
1
\end{bmatrix}
\mapsto
\begin{bmatrix}
4\\
5\\
1
\end{bmatrix},
\]
capturing exactly the reallocation needed at recursive calls [2509.22982].

This representation turns inference into algebra. Primitive operations such as `Move`, `shift`, and `unshift` are themselves matrices; typing judgments collect sets of path matrices \(\mathcal S\) and scope-exit matrices \(\mathfrak C\); and the function rule constrains candidate \(M\) by matrix inequalities. Under common first-order conditions these inequalities are linear, so candidate maps can be inferred with off-the-shelf linear-programming tools. Experimentally, when applicable, linear-map inference is “exponentially more efficient than the state-of-the-art algorithm,” and the synthetic benchmarks reduce from hundreds of millions of constraints and days of solving to hundreds of constraints and subsecond times [2509.22982].

The gain in efficiency comes with a boundary. The paper notes that linear maps cannot exactly represent genuinely nonlinear cost-free behavior such as \(\min(a,b)\), and full sharing of potential can introduce nonlinear constraints. The proposed long-term direction is therefore hybrid: use linear-map inference where the cost-free behavior is algebraically linear and fall back to older iterative methods where necessary [2509.22982].

## 5. Types that certify cost bounds intrinsically

A stronger interpretation of cost-free types makes the type derivation itself a certified cost analysis. Resource-Bounded Martin-Löf Type Theory extends resource-bounded type theory to full MLTT with dependent types. Judgments carry an ambient budget \(r \in L\) and a synthesized bound \(b \in L\):
\[
\Gamma \vdash_{r;\,b} t : A.
\]
Dependent function types \(_{x:A}^{b(x)} B(x)\) attach argument-dependent cost bounds, and elimination includes the bound function evaluated at the actual argument. Inductive families such as \(Vec(A,n)\) and \(Fin(n)\) propagate size information directly into those bounds [2601.10772].

The formal guarantee is the cost soundness theorem:
\[
\text{If } \cdot \vdash_{r;\,b} t : A,\text{ then }\exists v,k.\ t \; v \triangleright k \text{ and } k \preceq b.
\]
Evaluation is given by a big-step, costed relation \(t \Downarrow v \triangleright k\), and the theorem states that typing derivations over-approximate operational costs. The paper illustrates this with terms whose types explicitly express asymptotic bounds, such as
\[
\mathsf{sum} : _{n:N}^{\bot} Vec(N, n) \to^{3n + 2} N
\]
and
\[
\mathsf{bsearch} : _{n:N}^{\bot} Vec(N,n) \to N \to^{5 \cdot \lceil\log_2(n+1)\rceil + 3} \mathsf{Option}(Fin(n)).
\]
In this setting, the analysis is “for free” in the precise sense that no additional semantic analysis pass is required once the typing derivation is available [2601.10772].

Cost-Aware Type Theory develops a related but semantically different perspective. CATT introduces cost-aware judgments \(\isCComp{M}{A}{P}\) and the dependent function type
\[
\arrtimev{\isOf{a}{A}{B}{P},
\]
where \(P(a)\) is a term-level upper bound on the cost of computing the result at input \(a\). Ordinary extensional membership \(\isComp{M}{A}\) is therefore separated from cost-bounded membership. The paper emphasizes that standard function extensionality is “cost-free” because it identifies all functions with the same input-output behavior, regardless of their running time; the funtime type refines this by internalizing adherence to a cost specification as part of function typehood [2011.03660].

A third synthesis appears in “Potential Functions as Types.” Calf proves a fracture-and-gluing theorem for computation types:
\[
\CC = \DSumV{\A[\cl] : \CC[\cl]}{\DSumV{\A[\op] : \CC[\op]}{\LolliV{\A[\cl]}{\ClosedC{\A[\op]}}.
\]
Every computation type is thus equivalent to a concrete cost algebra, an abstract cost algebra, and an abstraction homomorphism. For potential functions this yields the type constructor
\[
\PotentialC{\X}{\Phi} \isdef \GlueeC{\F{\X}}{\F{\X}}{\varphi(\Phi)},
\]
so that homomorphisms between potential types satisfy the physicist’s conservation equation
\[
c_{\top}(x) + \Phi_{\Y}(f(x)) = \Phi_{\X}(x) + c_{\ABS}(x).
\]
The same framework defines credits \(\Credit{c}{\A}\), debits \(\Debit{c}{\A}\), and the graded substructural theory Giralf, whose semantics recovers AARA-style soundness
\[
p + \Phi_{\A}(e(\delta)) \le \Phi_{\CMP*{\otimes}\DeltaC}(\delta) + q.
\]
Here the phrase “potential functions as types” is exact rather than metaphorical: the potential function is built into the type structure itself [2607.08547].

## 6. Proof-theoretic and semantic variants

In theorem proving, cost-free types can mean that types no longer obstruct proofs. ACL2’s fixtype discipline defines a fixing function `fix` for a unary predicate `typep` such that
\[
\forall x\;.\; \mathit{typep}(\mathit{fix}(x))
\quad\text{and}\quad
\forall x\;.\; \mathit{typep}(x) \Rightarrow \mathit{fix}(x) = x.
\]
This induces an equivalence \(x \equiv y\) iff \(\mathit{fix}(x) = \mathit{fix}(y)\). If a conjecture \(C(x)\) is congruent with respect to that equivalence, then Theorem 1 states that \(C(x)\) is a theorem iff \(\mathit{typep}(x) \Rightarrow C(x)\) is a theorem. The practical effect is that type hypotheses can disappear from theorems without loss of correctness, reducing proof-search overhead and simplifying rewrite rules [1509.06079].

A semantic analogue arises in quantitative parametricity. “Improvements for Free” extends relational parametricity with cost-lifted semantics, interpreting values as pairs \((v,c)\) and logical relations at function types as relations preserving both extensional behavior and cost structure. This yields quantitative free theorems from polymorphic types alone. For
\[
f :: \forall \alpha.\, \alpha \to \alpha \to \alpha,
\]
the paper derives that
\[
g\,(f[\tau_1/\alpha]\,t_1\,t_2) \sqsubseteq f[\tau_2/\alpha]\,(g\,t_1)\,(g\,t_2),
\]
and the cost difference is exactly either \(\Delta(g,t_1)\) or \(\Delta(g,t_2)\). For \([\alpha]\to Nat\), it derives that applying `map g` before a polymorphic consumer cannot make the computation cheaper. These are cost-related properties obtained “for free” from types, but they depend on a call-by-value cost semantics and the uniformity enforced by polymorphism [1107.1203].

“The Geometry of Types” occupies a different point in the design space. Its linear dependent types for PCF infer both a type and a cost expression called the weight, together with an equational program and proof obligations. The output judgment is derivable iff all proof obligations are valid. Complexity analysis is thereby reduced to checking first-order inequalities, and relative completeness ensures that no information is lost. This is not a zero-cost coercion story; rather, it is a type-based relocation of complexity reasoning from higher-order operational behavior to first-order arithmetic side conditions [1210.6857].

Across these variants, the recurring theme is stable. Types may be made cost-free operationally, as in transient gradual typing or zero-cost coercions; cost-free analytically, as in AARA’s homogeneous potential transfer; cost-free proof-theoretically, as in fixtypes; or intrinsically cost-carrying, so that the type derivation itself certifies complexity. The literature does not collapse these senses into one definition, but it consistently treats types as a mechanism for obtaining stronger guarantees with sharply reduced overhead in some other dimension [1807.00661], [1803.08150], [2509.22982], [1509.06079], [2601.10772].

Source: https://www.emergentmind.com/topics/cost-free-types