Polynomial Time and Dependent Types

We combine dependent types with linear type systems that soundly and completely capture polynomial time computation. We explore two systems for capturing polynomial time: one system that disallows construction of iterable data, and one, based on the LFPL system of Martin Hofmann, that controls construction via a payment method. Both of these are extended to full dependent types via Quantitative Type Theory, allowing for arbitrary computation in types alongside guaranteed polynomial time computation in terms. We prove the soundness of the systems using a realisability technique due to Dal Lago and Hofmann. Our long-term goal is to combine the extensional reasoning of type theory with intensional reasoning about the resources intrinsically consumed by programs. This paper is a step along this path, which we hope will lead both to practical systems for reasoning about programs' resource usage, and to theoretical use as a form of synthetic computational complexity theory.


INTRODUCTION
Type Theory is often claimed to be ideal for Computer Science, combining programming and proof in one unifying system, so a happy programmer can verify while they program, and program while they verify.From a broader Computer Science view, however, Type Theory lacks the ability to talk about the very thing that makes Computer Science interesting -the fact that computation is everywhere bounded by the resources in time and space that we can afford to give it.
Typically, Type Theory only speaks of the public face that programs present to the world -if you input things like this, you get things that look like that -but cannot bring itself to mention the true cost of programs' execution.One can encode costs by embedding another programming language in Type Theory, for example [Guéneau et al. 2018], or one can synthesise costs by treating resource counting as a computational effect, for example [Danielsson 2008;Niu et al. 2022], but neither of these capture the intrinsic costs of the programs we write in Type Theory.These techniques deliver only conspicuous consumption, not speaking of the real resources consumed.
In this paper, we propose a method for extending dependent Type Theory with a means for constraining the intrinsic computational complexity of programs written in the theory.We concentrate on linear type systems that soundly and completely capture polynomial time computation, the commonly used standard for feasible resource usage, and extend these systems to dependent types.The additional expressivity of dependent types allows us use these characterisations of polytime to further functionally characterise the classes of non-deterministic and bounded-error probabilistic polynomial time.
We use techniques from Implicit Computational Complexity theory, which provides intrinsic characterisations of complexity classes in terms of logical systems or programming languages.We review the techniques that we use in Section 2. To adapt these systems to dependent types, we use Quantitative Type Theory (QTT) [Atkey 2018;McBride 2016], a combination of linear and dependent types.We review QTT in Section 3.
Our long-term goal is to combine the extensional reasoning of Type Theory with intensional reasoning about the resources intrinsically consumed by programs.This paper is a first step along this path, which we hope will lead both to practical systems for reasoning about programs' resource usage as well as their extensional behaviour, and to theoretical use as a form of synthetic computational complexity theory.We discuss these possibilities further in Section 7.

Contributions and Content
This paper makes the following contributions to the theory and use of linear dependent type theory and implicit computational complexity: (1) We formulate two systems that combine linear type theory for polytime computation with full dependent types, using Quantitative Type Theory.The systems are presented in Section 3. The linear typing discipline required for enforcing polytime is provided by QTT, but we also need to carefully add constructs for non-iterable datatypes (Section 3.2) and the two kinds of natural number iterator that we consider (Section 3.3 and Section 3.4).Porting the natural number iterators from the simply typed to the dependently typed setting requires careful annotation of the rules to ensure that the correct information is available for type checking, while also not allowing too much information to be made available at runtime that would violate the polytime soundness property.A further contribution of this paper is the addition of reflection types to QTT, Section 3.5, which allow statements about polytime realisability to be reflected into types.
(2) We demonstrate the utility of the combination of polytime and dependent types in Section 4.
Just as in the simply typed world, we have an expressive language for writing polytime programs.With the additional power of dependent types, we can also prove properties of these programs.A simple example is proving that a polytime sorting program actually sorts.Using QTT reflection, we can go further and represent the class of polytime problems, with polytime reductions between them, as dependent pairs (Section 4.2).Our final examples use dependent types to give monadic presentations of the complexity classes of Non-deterministic Polynomial (NP) time and Bounded-error Probabilistic Polynomial (BPP) time.Since these classes rely on specific semantic correctness criteria, it is not possible to capture them in a simply typed system for polytime.(3) We prove the polytime soundness of our systems via a realisability argument in Section 5 and Section 6.Our construction is an extension of the amortised complexity realisability constructions of Dal Lago and Hofmann [2011].We extend their work to our dependently typed setting, and also give a realisability interpretation of datatypes directly, instead of via second-order impredicative encodings.The technical content of these sections has been formalised in the Agda proof assistant [Norell 2008], and is included in the associated artefact [Atkey 2023].
Before we get to the contributions above, we present, in Section 2, two linear simply typed systems for polytime, adaptations of systems already present in the literature.Our paper concludes with a discussion of further related work and the outlook for future work in Section 7.

AFFINE LINEAR TYPING AND POLYTIME
Not long after Girard introduced Linear Logic [Girard 1987], it was observed that its resource sensitivity could be turned to describing computational complexity classes by purely logical means.Typically, a logical system is described for which the process of reducing a proof to a normal form (often by cut elimination) is guaranteed to always be accomplished within a certain complexity bound.Moreover, the system is usually proven to be complete for the relevant complexity class by constructing a simulation of some known representation.Such systems that characterise polytime include Bounded Linear Logic (BLL), which uses explicit polynomials in the formulas [Girard et al. 1992] and Soft Affine Logic (SAL) [Lafont 2004], which does not explicitly represent time information in formulas, but uses a restricted form of Linear Logic's !modality instead.Light Linear Logic (LLL) [Girard 1998] is another "counting-free" system for polytime.
Viewing logical systems though the Curry-Howard correspondence, the idea arises that one could define functional programming languages that characterise complexity classes such as polytime.SAL has been transformed into a programming language by Baillot and Mogbil [2004], and likewise for LLL by Baillot et al. [2010].Hofmann [1999] proposed a new programming language, Linear Functional Programming Language (LFPL), that uses a novel "payment" system to track iteration.
There are at least two ways that a functional programming language can be seen as representing polynomial time, differing in how the size of the problem to be computed is measured.One approach is to consider closed expressions, combining the program with its input, and computation of the result is polynomial time in the combined size.A second approach is that the input is "externally" provided, where we consider open terms with a free variable representing the input.So a judgement : Nat ⊢ : declares a program that computes results of type in time polynomial in the size of the natural number .We take this latter approach in this paper.
With a view to extending to dependent types in Section 3, we take an approach slightly different to much of the polytime linear logic literature.We use explicit datatypes and eliminators, rather than using impredicative encodings via universal types.We are closer to Hofmann's original LFPL (though not a later presentation of it by Dal Lago and Hofmann [2011]) than BLL, SAL or LLL.
In this section, we review the use of linear types to capture polytime by presenting two systems, one based on ideas from SAL and the second more explicitly based on LFPL.

Affine Linear -Calculus
For this section, the affine linear -calculus we will use will have linear functions and ⊗-products.Contexts are treated up to permutation of entries, so uses of exchange are implicit.
Γ, : ⊢ : These rules are standard, so we do not describe them further except to note how affine linear typing uses presence or absences in a context to control resource usage.If a variable is in the context it must be used at most once (variables that are not used are absorbed by the additional context in the variable rule).The fact that this discipline interferes with dependent types is one of the reasons we turn to QTT when we wish to add dependent types in Section 3.

No Recursion, Only Case Analysis
It is not too difficult to see that reduction of linear -terms always takes a number of steps linearly proportional to the size of the term.This is because every -redex substitutes each term into at most one variable, reducing the size of the term by one each time.
We can increase the expressivity, but not the computational complexity, of the system by adding datatypes that do not allow iteration.These can be used for representation but not for driving computation.We include the rules here to show how linearity must be preserved in these rules and to foreshadow their dependently typed counterparts in Section 3.2.The first type is the booleans, which are non-recursive and so would not allow iteration anyway: The if-then-else rule is careful to ensure that the resources used by the eliminated Bool and the resources used by the chosen branch are accounted for separately.The two branches must have the same resource usage.
Construction and case analysis of lists are given by the following rules: We can construct lists arbitrarily but only do case analysis on them.If we wish to explore a list to a arbitrary depth it must be driven by a type we can iterate over.
With booleans and lists, we can construct several other useful types.For example, to simulate Turing machines, one can construct a Tape type as a Zipper (Huet [1997]) List(Bool) ⊗ Bool ⊗ List(Bool), representing a position on the tape with the items before, under, and after the head.

The Cons-free System
Polynomial time is usually seen as a proxy for "feasible" computation.On the face of it, there does not seem to be any particular reason why polynomials have anything to do with feasibility.However, one can arrive at the definition of polynomial time in three steps, by assuming that (i) iterating over the whole input is feasible; (ii) if two computations are feasible, then so is their composition; and (iii) performing a feasible computation for every element of the input is also feasible.It is the last point that allows complexities of arbitrary polynomial degree to be constructed (we will see this in action in the completeness construction below and soundness proofs in Section 6).
Following these ideas, let us assume that the input is a natural number, so we assume that there is some type of natural numbers Nat.For point (i), we must be able to iterate over these natural numbers, so we use a linear iterator defined by this typing rule: Note that in the zero, , and sucessor, , cases, the context is empty to ensure that these cases may be invoked as many times as required.Point (ii) above is automatically satisfied by being in a typed -calculus, where it is difficult to stop functions from being composable.For point (iii), the iterator as given does not allow us to nest iterations.Once the natural number input has been used for an iteration, the linear typing discipine prevents us from using it again (note the two separate contexts Γ 1 , Γ 2 in the rule for application).In order to allow nested iterations, we add an operator to duplicate numbers: Somewhat surprisingly, this system is now sound and complete for polynomial time.Crucially, this depends on the two things we have not allowed.First, we have disallowed the construction of new natural numbers via the zero and succ constructors1 .If we were to permit this, then we could use iteration over the input to construct addition, multiplication (by repeated addition), and then exponentials (by repeated multiplication).We therefore refer to this system as the Cons-free system.Because we cannot construct values of type Nat within the system, complete programs in this system are open terms as we explained at the start of this section.
The second prohibited feature is the ability to duplicate values of function type, even though we have allowed duplication of iterable naturals.If we were to allow this, then we would be able to sneak in a form of constructors for natural numbers by encoding them as eliminators that duplicate a function for every succ step.
We will see in Section 6.2 that this system is sound for polytime by a realisability argument.Completeness can be seen more directly by constructing a function that iterates a function for a statically known polynomial number of times in the size of the input.Assume that we have a known polynomial ( ) = + • • • + 0 of degree with natural number coefficients and some single step function : St ⊸ St over a state type St that runs to completion for input of size in ( ) steps.Then, using the iterator above we can iterate over a Nat representing the size of the input: To achieve higher degrees, we can use dupNat to nest iterations: By further use of dupNat and composition to handle addition of polynomials, the function can now be iterated ( ) many times, where is the input Nat.Thus, the Cons-free system can represent all polytime computations.

Diamond Trading with LFPL
The Cons-free system is sound and complete for polytime, but is quite awkward from the point of view of functional programming.It allows us to iterate over natural numbers that come from the input but does not allow us to build further values to do iteration on.For example, if our input is a list, then we cannot transform it into a binary search tree and then flatten it, we must always refer back to the original natural number input.Even dividing the input into two halves to be treated separately is difficult.A more flexible system was proposed by Hofmann [1999].Instead of completely prohibiting construction of data, the Linear Functional Programming Language (LFPL) allows construction if it is paid for by values of type ("diamonds"): To construct a zero, we must have a to pay for it, and likewise, to construct a succ we must pay a .We can think of s as an unit of iterable data.Iterability is "saved up" in data during construction, and released during iteration.Diamonds cannot be created by a program itself, for the same reason that constructors were prohibited in the Cons-free system, but they are released from iterable data during iteration.The LFPL natural number iterator has the following typing rule: The difference with the Cons-free iterator above is that the zero and succ cases now both have an additional binding of type .This allows some form nesting of iterations: during an iteration over the input, the program can accumulate s to use for iteration over substructures that are smaller than the current point in the iteration.A construction, due to Aehlig and Schwichtenberg [2002], illustrates how this leads to all polytime computations.As above, we assume a polynomial ( ) and a step function : St ⊸ St that needs to be iterated ( ) times.We construct a linear iterator: Note that this iterator returns the natural number input as well as the new state.LFPL does not allow duplication of iterable inputs, so we must always reconstruct it if we want to do further iteration.Addition of polynomials is accomplished by composition of iterators.To raise the degree, we again use a nesting iterator: Unlike in the Cons-free system, this iterator does not raise the degree of the nested iterator directly.Rather, the iterator on the input performs iterations.As observed by Aehlig and Schwictenberg, this is sufficient because the binomials form a basis for the vector space of all polynomials.
Despite this slightly more involved completeness construction, the advantage of LFPL is that it is now easy to have arbitrary iterable datatypes and to transform between them.We need only take the introduction and elimination rules for any inductive datatype and add premises to the introduction rules and bindings to the eliminators.

POLYTIME QUANTITATIVE TYPE THEORY
We have now seen the Cons-free and LFPL systems for capturing polytime by means of linear typing and restricted iteration.We now look to extend these systems to include dependent types by building upon Quantitative Type Theory (QTT) [Atkey 2018;McBride 2016].This section reviews QTT and describes how we have adapted it to the polytime systems we saw in the previous section.

3.1
antitative Type Theory Integrating linear and dependent types is not straightforward due to the conflict between the linear typing discipline regarding presence of a variable as only bestowing the right to use it once, and the dependent typing regime that uses variables both in types (for specification purposes) and in terms (for computational purposes), syntactically yielding multiple uses of the same variable.
QTT is a system that resolves this conflict by recording usage of variables with annotations from a semiring.It sits in the general area of systems that use semiring annotations to measure resource usage [Brunel et al. 2014;Ghica and Smith 2014;Orchard et al. 2019].The key feature of QTT, an insight owing to McBride [2016], is that usage of variables in types counts for 0-usage in terms of the semiring used.This allows us to use normal type theory as a specification language, while also enjoying the benefits of linear typing for programs.The term typing judgement of QTT has the following form: where the annotations are all from the semiring being used.The annotation is either 0 or 1, indicating whether we are in the erased ( = 0) fragment, where all the normal rules of type theory apply, or the in the non-erased ("present", "realisable", = 1) fragment, where a restricted typing discipline applies.As we shall see below in the cases of Σ-types, iterable types, and LFPL's type, the separation of QTT into these two fragments allows an expressive combination of reasoning using full type theory with the benefits of linear typing.
In the remainder of this sub-section, we describe the core of QTT.As well as the term typing judgement given above, QTT also has judgements for well-formed contexts (Γ ctxt) and types (Γ ⊢ type), and definitional equality of types and terms (Γ ⊢ ≡ type and Γ ⊢ ≡ : ).It is an invariant of the system that types are always well-formed in a context with all annotations 0, i.e., Γ ⊢ type implies 0Γ = Γ.An important admissible rule of the system, along with weakening and substitution, is that of 0-ing: This rule allows us to take any term in the = 1 fragment and treat it as if it were in the = 0 fragment, and hence use it for specification purposes in types.As we add novel rules to QTT in the following sections, we will be careful to maintain the admissibility of this rule.
In this section, we give an overview of the rules of QTT.The full rules, including all equality rules, are presented in Appendix A.
3.1.1Natural-number Usages.We use an instantiation of QTT with the natural number semiring, with the usual semiring structure of addition and multiplication.In a mild generalisation of the original presentation of QTT, we also allow sub-usaging via the reverse ordering on the naturals.That is, if a variable is marked as usage and ≥ , then we can also regard it as usage .This makes the system more like affine linear logic, since ⊑ 02 for all , matching the system in Section 2. We do not have an unrestricted usage , since this would allow the possibility of unrestricted duplication, and hence violate our polytime soundness properties.
3.1.2Contexts, Variables, and Conversion.As we saw above, contexts in QTT are comprised of variable : type triples, where is a natural number indicating how many times the variable is available for use in a = 1 term.There are two operations on raw contexts: scaling Γ, which multiplies each in Γ by , and addition Γ 1 + Γ 2 , which adds two contexts' usage annotations assuming that the lengths and types are equal.Contexts are ordered pointwise Γ ′ ⊑ Γ on the usage annotations (which is the reverse ordering on naturals) The basic usage-annotation discipline of QTT is demonstrated by the context formation and variable rules: As with most dependent type theories, contexts are built inductively from the empty context and extension of a context by a variable with a type that is well-formed in the preceding context.Usage annotations on variables are arbitrary, and types are always judged in a 0-annotated context.The variable rule marks unused variables as usage 0 and the selected variable with usage .
As usual, definitional equality of types impacts typing of terms via the conversion rule: Like type formation, definitional equality of types always takes place in 0-d contexts.We will describe the definitional equality rules for terms of each type as we introduce them.In QTT, it is possible for the definitional equality of terms to differ between the = 0 and = 1 fragments, as we will see below.
3.1.3Π-and Σ-types.QTT's Π-types have the form ( : ) → , indicating functions that, in the = 1 fragment, use their arguments -many times.The formation, introduction and elimination rules are similar to the standard ones, except for the addition of usage annotations: The side conditions on the elimination rule state that (i) both Γ 1 and Γ 2 erase to the same context, so their sum is defined; and (ii) the argument is erased (i.e., ′ = 0) iff either the function does not use its argument, or we are in the = 0 fragment and everything is being erased.In the following, when we write → for a non-dependent function type, we mean that the argument is to be used linearly: ) → , where does not appear in .Π-types support the usual definitional equalities in both the = 0 and = 1 fragments.
Σ-types are a little more involved, and demonstrate the flexibility in QTT in allowing additional power in the = 0 fragment where we do not need to care about polytime realisability.Formation and introduction are given by the rules: As with Π-types, the first component of a Σ-type is annotated with a usage for how many times it can be used, and this is respected by the introduction rule.Elimination of Σ-types depends on whether we are in the = 0 fragment or not.In the = 0 fragment, we are free to disregard usage restrictions, and use projections as normal: Σ-types are unrestricted in the = 0 fragment, and we can use them as normal for type-theoretic constructions.In the = 1 fragment, we must take into account the resource content of objects and use a pattern matching construct; the dependently typed analogue of the ⊗-eliminator in Section 2: QTT also supports a unit type with constructor * and pattern-matching [Atkey 2018].Σ-and types support the usual definitional equalities in the = 0 fragment (e.g., fst( , ) ≡ ), but only equalities (i.e., let ) in the = 1 fragment.It would also be sound to support commuting conversions [Barber 1996] for let in the = 1 fragment, but this would likely bring complications for implementation.

3.1.4
The Identity Type.QTT also supports an extensional equality type with equality reflection: The equality type also has an rule demonstrating refl( ) as the only proof of equality [Hofmann 1997].Note that equality reflection only targets the = 0 fragment, we cannot use equality reflection to convey realisability information.
3.1.5Universe.QTT has universe types U, as in standard type theory [Atkey 2018].For our examples below, we do not explicitly mark the use of terms of type U as types -i.e., we use a Russellstyle presentation.Universes are where the definitional equality on terms affects the definitional equality on types.
3.1.6Data Types.QTT, as we have presented it so far, has no interesting base types to perform computation on.Following our presentation of the simply typed linear systems in Section 2, we add two kinds of datatype to QTT.First, in Section 3.2, we add non-iterable datatypes that allow construction and case analysis, but no recursion.Then, in Section 3.3 we describe how to extend QTT to be a dependently typed adaptation of the Cons-free system of Section 2.3 by adding a type of iterable naturals.In Section 3.4 we apply the same treatment to the LFPL-style system.

Non-iterable Data Types
3.2.1 Booleans.The boolean type for QTT was described in [Atkey 2018].Booleans offer no possibility for iteration, but it is useful to see how the QTT rules extend the simply typed rules from Section 2.2 before moving to more complex types.
The introduction rules for booleans both use a 0-d context, indicating that construction of boolean values is free.Elimination of booleans via a dependently typed if-then-else is more subtle with its resource usage.The boolean to be eliminated must be constructed in a context Γ 1 , while the two branches are constructed in context Γ 2 .Since only one of the branches will be used, sharing resources between the branches is expected.Booleans and their eliminator obey the usual laws for definitional equality: if .true then else ≡ , and similarly for false.One might wonder how, since constructing booleans is 0-cost by their introduction rules, the Γ 1 context will ever be non-0.This is resolved by observing that booleans may be the output of processes that consume time (e.g., the iteration constructs defined below), and so Γ 1 will represent a requirement that the necessary resource is provided.
3.2.2Lists.Lists are a little more complex than booleans, because the cons constructor takes two arguments, so their resource usage must be combined.The type formation and introduction rules are as follows: Lists do have the potential for iteration by their recursive nature, but in order to ensure the polytime complexity guarantees we only permit matching without recursion in the = 1 fragment.
Here is the rule for dependently typed case analysis on lists, which also obeys the usual -equalities for case analysis, analogous to the ones for booleans: In the = 0 fragment, however, we are free to iterate on lists because computations in this fragment are only meant for type-level computation, not for the program itself.Put another way, the type checker may perform arbitary recursion on lists to type check the program, but the program itself may not do so without correctly accounting its costs as described in the following sections.The = 0 fragment recursor for lists has the following typing rule, which is the standard dependent eliminator for lists except that everything annotated as 0 usage.
This eliminator also obeys the usual -equality laws for a list eliminator, using the resource freedom of the = 0 fragment to duplicate the 2 term in the cons case.

Cons-free Natural Numbers and their Recursor
The datatypes of the previous section still only allow us to write programs in the = 1 fragment that are constant time in the size of their input.As with the simply typed linear system, if we are handed a list of an unknown length, we can only explore it to a fixed depth, determined statically by the program.To write programs that do work proportional to the size of their input, we need some form of iterable datatype.In both our Cons-free and LFPL-style QTT systems, we use a natural number datatype.
The Cons-free system cannot allow the programmer to construct natural numbers in the = 1 fragment, as this would violate the complexity guarantees.However, we can use the flexibility of QTT to allow free construction of naturals in the = 0 fragment, which allows us to use natural numbers freely in types.Therefore, we have the following introduction rules, only usable in the = 0 fragment: The cons-free system allows free duplication of complete natural numbers.This is accomplished by a special construct copying the simply linear typed rule we gave above: Anyone who has reasoned about the metatheory of, or implemented a type checker for, dependent types will view this rule with unease as it appears to grant the ability to construct non-canonical values of pair type, and consequently generate non-canonical naturals.We fix this by adding an equational rule to the = 0 fragment, ensuring definitionally that dupNat acts as its name implies: Note that this rule is well-typed by the 0-needs-0 property of QTT, and the fact that 0 + 0 = 0.The eliminator for these natural numbers takes the following form.Disregarding the usage annotations, it has the same type structure as the normal dependently typed recursor for naturals: In the successor case, , there are two bound variables: for the natural number and for its induction hypothesis.Note that is required to be usage 0 no matter what is.We need the variable to be present in order to correctly type the induction hypothesis and the conclusion, but it must be marked as usage 0 to ensure that the resources captured by the number are not duplicated.This eliminator cannot have a -equality in the = 1 fragment because there is no way to construct any natural numbers to iterate on in this fragment.In the = 0 fragment, this eliminator obeys the usual -equality laws for a natural number recursor.This allows us to use it to compute and reason about operations on naturals in this fragment.
The reader is invited to compare this dependently typed rule with the simply typed linear version in Section 2.3.Removing the 0-annotated parts of the rule, and the type dependency, yield the exact same rule.Conversely, when = 0, this rule is identical (up to 0-annotations) to the usual dependently typed recursor for natural numbers, and so we can use it in the types to prove properties of programs just as we do in normal type theory.We will see in Section 6.2 that this rule is realisable by polynomial-time computation, and so is sound for polynomial time.
3.4 LFPL-style Diamonds, Natural Numbers, and a Recursor that Gives Back As explained in Section 2.4, the LFPL system differs from the Cons-free system in that it is possible to construct natural numbers (and other iterable datatypes), provided one has the necessary diamonds to pay for the construction.As with the natural number type in the Cons-free system, it ought not be possible to construct diamonds in the = 1 fragment, as this would amount to the free distribution of diamonds to all which would lead to a collapse in the complexity guarantees of the system.It is possible construct diamonds in the = 0, though: The type also supports an -rule in the = 0 fragment, indicating that, in this fragment, it acts the same as a unit type.This allows us to freely use diamonds in types, and to not have to care about the identity of particular diamonds, since by this rule all diamonds are definitionally equal3 .
Construction of natural numbers now requires a for zero and a and a predecessor for succ: In the = 0 fragment, we can construct s for free, and so construct natural numbers freely as well just as we did for the Cons-free system above.The dependently typed recursor for LFPL-style natural numbers again augments the simply typed linear recursor from Section 2.4 with dependency information: We have used * : as the value in the types for the zero and successor cases.By the -rule for diamonds, we could have equally well used the variable that is in scope in each case.
Unlike the natural number iterator in the Cons-free system, this iterator has -equalities in both the = 0 and = 1 fragments.In the succ case, for example, we have: Note that the fact that the variable in the term is annotated 0, which allows us to use twice even when we are in the = 1 fragment.
Just as for the Cons-free system iterator above, in the = 0 fragment this rule is identical to the usual dependently typed recursor for the natural numbers, so it can be used in the types to reason about programs.Moreover, we will see in Section 6.3 that this rule is also sound for polynomial time in a system with s.

Reflection of Realisability
Our final addition to QTT is reflection of realisability.In QTT thus far, it has been possible to reason about the non-resourced behaviour of programs.This is because the 0-ing process moving from the = 1 fragment to the = 0 fragment erases all resource information.This is sufficient for reasoning about the extensional behaviour of programs via types, but it is useful to be able to make statements like "this function is realisable in polynomial time" in the types of QTT, something that is not currently possible with the system we have seen so far.
We remedy this by adding a realisable type to QTT with the following type formation and introduction and elimination rules: Intuitively, the type R( ) is inhabited whenever the type is realisable in the = 1 fragment of the system.In particular, the type R(Nat → Nat) is the type of all realisable functions from natural numbers to natural numbers.In the polynomial time systems we are concerned with here, this is exactly the type of polynomial functions.Note that in the introduction rule, the premise is required to be in the = 1 fragment, to ensure that the type is realisable, while in the elimination rule, the conclusion is in an arbitrary fragment ′ .This flexibility is require to maintain the admissibility of the 0-ing rule.
The equality rules for R state that the two operations are mutually inverse: R(R −1 ( )) ≡ , in both fragments, and R −1 (R( )) ≡ in the = 0 fragment.By congruence, the = 1 fragment's definitional equality affects the definitional equality of the = 0 fragment via the R(−) constructor.
With just the rules given here, the type R( ) is no more than a statement that a given type is realisable with a polytime implementation.This is enough to do the constructions that we present in the next section, e.g., that polytime functions are closed under composition, but one could imagine stronger reflection principles that allow deeper logical consequences of polytime realisability to be proved internally.We discuss this further in Section 7.2.
Readers familiar with Benton [1994]'s Linear/Non-linear system will note that the R( ) constructor is the QTT analogue of the right adjont type constructor in that system.The Σ-types play the role of the left adjoint types, in a similar way to the dependent linear type system of Krishnaswami et al. [2015].

PROGRAMMING AND PROVING WITH POLYTIME
We now explore the possibilities afforded by the combination of polytime guarantees with the specification expressivity of dependent types.

Building Data Types
We have only defined an iterable natural number datatype for both of our systems above.We could extend both systems to include further iterable inductive types, although in the Cons-free system this is not particularly useful due to the prohibition of construction.However, sticking with just the natural numbers, we can use the power of dependent types with a universe to create further datatypes whose size is measured by some iterable natural number.Iteration on the size yields iteration over the full datastructure.For example, in the LFPL system, we can define a type of iterable lists by pairing a size with a type of elements defined by recursion on the size: The nil and cons constructors can now be defined in terms of zero and succ, provided the caller supplies sufficient s.These definitions live in the = 1 fragment, so we annotate them appropriately: Using the LFPL iterator it is also possible to construct a dependently typed iterator for IList values.Unfortunately, the current types of the LFPL system are not sufficient to type this as a function, as we have no way of stating that the successor case must be arbitrarily duplicable.Lifting this restriction by means of some modality is future work.The typing rule for the derived list iterator is: Note that, in the cons case, we have access to the result of iterating over the tail of the list ( ), but not to the actual tail of the list (xs).
With our list iterator, it is now possible to write interesting polytime programs.For example, the example used by Hofmann [2003] to demonstrate the expressivity of LFPL is insertion sort.First we define insertion of a natural into a sorted list: which requires some ingenuity to write to handle the case where we find the place to insert the item and need access to the remainder of the list.Note that, also, the function consumes a to construct the new element of the output list, and also that the items in the list are themselves iterable natural numbers.This is needed to account for the comparisons between elements.
Insertion sort is repeated insertion of elements from an original list into a new list.The new list is constructed from the s yielded by the original list: The immediate benefit of dependent types in this situation is that it is now possible to state and prove the correctness property of this sorting procedure.Using the fact that the = 0 fragment of QTT is exactly normal type theory, we can use normal dependently typed programmming techniques to establish: where Sorted( , ) is some predicate stating that is a sorted permutation of .Note that, despite the 1 annotation on the Π-type here, we are free to duplicate xs because types are constructed in the = 0 fragment.

Polytime Problems
Define a decision problem to be a pair ( , ), where is a type in the universe U, and : → U is a predicate on .For what follows, we are only interested in whether or not is inhabited for each .Therefore, we use ⇔ to stand for equi-inhabitation of two , : U, i.e., ⇔ ≡ ( → ) × ( → ).
We can use the reflection type former defined in Section 3.5 to define a predicate on decision problems that establishes whether or not they are polytime decision problems.Specifically, we can state that there is a polytime realisable boolean-value predicate that reports true exactly when the given element of is in the predicate: Thus, PTIME( , ) is a logical proposition stating that the decision problem ( , ) is decidable in polytime.We make three notes about this definition: (i) proofs of PTIME( , ), are carried out in the = 0 fragment, where we have the full power of Type Theory to aid us; (ii) this definition is intrinsic, in the sense that, whichever of the polytime systems is chosen, proving that a decision problem is solvable in polytime is a matter of programming, without having to reason directly about machine models and step counting; and (iii) we have defined problems to have arbitrary types as domains, rather than bitstrings, and so the notion of size attached to an input is intrinsic to the type chosen.
We can also declare a type of polytime reductions between problems.A problem ( , ) can be polytime reduced to a problem ( , ) if there is an inhabitant of the following type: In words, there must be a polytime function that preserves and reflects decisions.With this definition, it is possible to prove in our systems that polytime computations are closed under polytime reductions.We note that this definition is, up to the reflection modality, the same as the definition of cartesian container morphism, well known in dependent type theory [Abbott et al. 2005], and speaks to a general conception of containers as "problem/solution" pairings and container morphisms as problem reductions.

Polytime-based Complexity Classes
The fact that we can characterise polytime decision problems is perhaps to be expected from a system designed to capture polynomial time realisable programs.However, we can go further to capture the complexity classes of Non-deterministic Polynomial time (NP) and Probabilistic Polynomial time (PP), both of which are based on polytime.We do this by augmenting our polytime functions with additional power in the form of computational effects.

Non-deterministic Polynomial Time.
To capture the complexity class NP, we use polynomial time programs augmented with non-determinism, as one might expect.We will not need to reason about equality of these non-deterministic programs, so we can represent non-deterministic choices as binary trees.We suppose a non-iterable datatype defined like so: The crucial point here is that the subtrees are represented as a function Bool → ND .By the typing rules of QTT, this means that the two branches of this function can share resources (see the encoding of the additive product types by Atkey [2018]).Thus, each branch of this tree can be explored in polynomial time, but not the whole tree itself.
The type ND supports a monad interface via the usual free monad construction, as well as an effect flip 1 : ND Bool providing access to a bit of non-deterministic information.Thus a program of type → ND in the = 1 fragment will be a polytime program with access to an oracle.In the = 0 fragment, we can write a function that resolves non-determinism using a list of booleans.This function returns nothing if the list of booleans is insufficient to resolve all the choices: With these definitions, we can define Non-deterministic Polynomial time as a predicate on problems: Thus, a problem is in NP if there is a non-deterministic boolean-valued polynomial time function that has a path to returning true exactly when the input satisfies the predicate.Moreover, it is a quick matter of programming to see that problems in NP are closed under the type of polytime reductions given above.
As in the non-deterministic case, a function → Dist in the = 1 fragment is a polytime probabilistic computation.Again, the use of a function type here ensures that each branch of the tree is constructable in polynomial time, not the whole tree.In the = 0 fragment we can write a function that computes the probability of a Dist Bool computation being true: We can now define the class of probabilistic polynomial time decision problems, where the decider is allowed to make probabilistic choices as long as it is correct with probability at least 2 3 : Again, problems in BPP are easily seen to be closed under polytime reductions.Probabilistic Polynomial time has previously been considered in the setting of implicit computational complexity by Dal Lago et al. [2021] and Dal Lago and Toldin [2015].In both cases, they must build probabilistic choice into the language, and have difficulty in directly capturing the class BPP due to its semantic nature, where the correctness of implementation is probabilistic.With a dependently-typed host language, adding probabilistic choice as an effect and capturing the semantic constraint of BPP is straightforward.

POLYTIME SOUNDNESS VIA REALISABILITY
In this section and the next, we establish the polytime soundness of our extensions of QTT by adapting a realisability method due to Dal Lago and Hofmann [2011].This approach is based on a three way coupling between abstract mathematical elements (the what), values from a machine model (the how), and resource potentials (the fuel).Each type in the system is defined as a three way relation between these elements.The set of abstract elements depends on the type being interpreted (e.g., types of natural numbers will be defined in terms of the set N).The machine model is fixed across all types.We describe the particular machine model we use for this paper in Section 5.1.Potentials are arranged into resource monoids that we define in Section 5.2.Unlike Dal Lago and Hofmann [2011], we explicitly construct realisers for inductive datatypes (both iterable and non-iterable) instead of relying on second-order polymorphic encodings and special !-stylemodalities.These explicit constructions are essential to construct models of our systems.
Agda Formalisation.The key soundness results in this section have been formalised in the Agda proof assistant [Norell 2008].The Agda formalisation can be found in the associated artefact [Atkey 2023].After each definition and result we provide a pointer to the Agda modules where the corresponding formalisation can be found, and note interesting features of the mechanisation.

Machine Model and Operational Semantics
We demonstrate that every program that can be written in extensions of QTT has the complexity bounds that we claim by translating QTT terms into an untyped CBV -calculus with a costed operational semantics.The syntax and rules of our target language are given in Figure 1.
Variables are represented as de Bruijn indicies , .Expressions ∈ E can be (anonymous)abstractions, unit, pairing and boolean values, variables, sequencing, application, pair elimination, and conditionals.Note that, with the exception of -abstraction and sequencing, expressions never contain nested expressions; instead referring to variables already defined.Values ∈ V can be closures clo , , where is an environment for the closure, unit values, pairs and booleans.
Costed evaluation of expressions in environments is defined by a big-step operational semantics , ⇓ , where is the number of steps.For simplicity, all operations cost 1 unit, though this could be generalised to allow for different operations to have different costs.We use [ ] to access the th variable in the environment, counting from the right.The evaluation rules are mostly as one would expect, except for the application rule which includes a self reference to the closure being invoked, in order to allow recursive definitions.
Agda Formalisation.The machine model is defined in the Agda module MachineModel.We use an intrinsically well-scoped syntax, which ensures that all variable look up operations are always well defined.

Resource Monoids
As we mentioned above, resource potentials are attached to values to represent the amount of intrinsic potential they have to fuel computation.Resource potentials are organised into resource monoids.To be able to account for the combined potential attached to composite data and programs (e.g., pairs, or functions applied to arguments) we will require monoid structure on potentials.The action of turning potential difference into fuel for computation will be modelled by a difference function.Finally, we require that our resource monoid contains sufficient elements to fuel constant time operations.We gather these requirements into a formal definition as follows, which is a slight reformulation of the resource monoids of Dal Lago and Hofmann [2011]: Definition 5.1.A resource monoid consists of: The latter is a "reverse triangle inequality": the fuel recoverable by moving between potential levels and via may be less than the fuel recoverable moving from to directly.( 4 Alternative definition.Every resource monoid induces a pre-ordering on its carrier set by ≤ iff 0 ≤ ( , ).Taking this idea further, we can reformulate a resource monoid as a symmetric monoidal category enriched in the symmetric monoidal category N −∞ , where the monoid structure is addition.The conditions in the definition above amount to the usual identity and composition laws for enriched categories.With this reading, we can see the value ( , ) when it is ≥ 0 as the possibility of moving from to levels of potential resource with some amount of residual resource emitted for computation; when it is −∞, moving from to is not possible.

Evaluation: Variable access and Sequencing
Agda Formalisation.Resource monoids are defined in the module Algebra.ResourceMonoid.We use a formulation closer to the enriched category theory definition for the actual formalisation, because it avoids having to treat equality in the monoid structure separately from the induced preorder on elements.Thinking of proofs involving the resource monoid as a process of finding a composable sequence of morphisms in a category was a helpful intuition when constructing the realisability model below.

Specific Resource Monoids.
The simplest example of a resource monoid is given by the natural numbers N, where each number stands directly an amount of stored fuel.
Definition 5.2 (Natural Number Resource Monoid).Monoid structure is given by normal addition.Differencing is defined as otherwise and acct ( ) = .Note that this is the simplest possible resource monoid due to the requirement that the acct function must exist.
The differencing operator of the natural number resource monoid can only supply as much fuel as is contained in the potential.For the two polynomial time systems, we need more sophisticated structures, both originally presented by Dal Lago and Hofmann.The fundamental idea with both is to represent potentials as pairs ( , ), where is a natural number and is a polynomial.The tracks the "size" of data as it pertains to the number of times an operation will be repeated by iterating over it -for example, an iterable natural number will have size equal to itself, but a noniterable natural number may be assigned zero size.The polynomial tracks the complexity of a program as a function of the size of the input.This leads to a differencing operator that evaluates the polynomial with the size of the data: Definition 5.3 (Polynomial Resource Monoids).The Max-Polynomial resource monoid MaxPoly has carrier set consisting of pairs ( , ) where is natural number and is a polynomial with natural number coefficients.Addition of elements is defined as ( , ) ⊕ ( , ) = ( ⊔ , + ), where ⊔ is the max operator, with ∅ = (0, 0).Difference is defined as: MaxPoly accounts for constant time with constant polynomials: acct ( ) = (0, .).
The Plus-Polynomial resource monoid PlusPoly is defined the same way as MaxPoly except that the monoid addition adds the natural number components instead of taking their maximum: ( , ) ⊕ ( , ) = ( + , + ).
It is perhaps easier to see how the differencing operator works in the special case of the difference MaxPoly(( , ), (0, 0)) = ( ).I.e., if we have code that contains data of size and a program with complexity , then running the combination with no expectation of remaining potential yields ( ) available steps.The MaxPoly and PlusPoly resource monoids will be used for the Cons-free and LFPL-style systems respectively, as we explain in Section 6 and show how these resource monoids yield the required polytime bounds on programs.
Agda Formalisation.The N resource monoid is defined in Algebra.ResourceMonoid.Nat and the polynomial monoids are both defined in Algebra.ResourceMonoid.Polynomial.The definition is parameterised by the "size monoid" operation (either ⊔ or +) used to compose sizes.

Resource sub-monoids.
The separation between sizes of data and complexity of code in the polynomial resource monoids motivates the use of resource sub-monoids to ensure that programs themselves (as opposed to higher order code which may contain closed over data) do not contain data that can be iterated.We do this by requiring that programs' potential must come from a specified resource sub-monoid: Definition 5.4 (Resource Sub-Monoids).A resource sub-monoid 0 ⊆ of a resource monoid consists of a subset | 0 | ⊆ | | that is closed under the monoid operations and acct.
For both MaxPoly and PlusPoly, the elements with zero size component, i.e., of the form (0, ), form a resource sub-monoid that we will use for interpreting programs.We will call these submonoids MaxPoly 0 and PlusPoly 0 .

Models of
antitative Type Theory from Indexed Preorders Atkey [2018] described a general class of QTT models termed Quantitative Categories with Families (QCwFs).Atkey [2018] constructs QCwFs from certain Linear Combinatory Algebras (LCAs), where terms in the = 1 fragment are realised by elements of the LCA.However, there is a mistake in that paper where the interpretation of contexts is stated to be the category of assemblies over the LCA, where it ought to be the category of sets paired with realisability relations, with no guarantee that all elements be realisable.
Here, we fix the mistake of Atkey [2018] and provide a more general construction of QCwFs in terms of indexed linear preorders.We construct indexed linear preorders specific to our polytime setting below.They could also be constructed from LCAs.
Definition 5.5.A N-linear preorder4 is a preordered set ( , ≤): (1) a commutative monoid ( , − ⊗ −) that is monotone w.r.t. the order; (2) is closed: there is an operation ⊸: × → such that ⊗ ≤ iff ≤ ⊸ ; and (3) has a function !: N → → , to interpret resource requirement adjustments, satisfying: The collection of all linear preorders and functions that preserve the order and the operations forms a category LinPreorder.
Given an indexed linear preorder : Set op → LinPreorder, we construct a QCwF model of QTT with the basic type formers from Section 3.1: (1) Define a category L of interpretations of contexts with objects that are pairs ( ∈ Set, ∈ ( )) and morphisms : ( , ) → ( , ) that are functions : → such that ≤ * (this is the Grothendieck category of ).There is a faithful functor : L → Set.The category L will be used for interpreting contexts in the = 1 fragment of QTT.
(2) Define scaling of objects of L by ( , ) = ( , ! ), and addition of ( , ) and ( , ) as ( , ⊗ ).where ev : ) is defined using application of .( 7) Universe and Equality types are interpreted as normal in Set with the realisability component set to in both cases.Note that the universe of small types includes resource-relevant realisability information for each type.(8) Realisability reflection for a type ( , ) ∈ Ty( ) is interpreted as the type ( .{∈ ( ) | ≤ ( .( , )) * }, ).Thus the set-component of the type is restricted to the elements that are realisable, while the actual realisability component is the "empty" realisability specification.
Agda Formalisation.The indexed linear preorders are defined in the Agda module IndexedLinear.We have not yet completed a formalisation of the construction of a full model of QTT from an indexed linear preorder so this part is currently unmechanised.

Amortised Complexity Realisability Model
Equipped with our underlying costed model of computation (Section 5.1) and a compositional notion of resource potential (Section 5.2), we can construct models of QTT that witness the resource and type soundness of our complexity constrained systems.We fix a resource monoid with sub-monoid 0 and proceed to build an indexed linear preorder of resource accounted realisers.5.4.1 Indexed Linear Preorder.We now define an indexed linear poset of realisers over Set that ties together our "mathematical" model of types in Set with our machine model and resource monoid.This construction is a reformulation of Dal Lago and Hofmann [2011]'s realisability models to make it suitable for dependent types.For a set , the carrier of ( ) is the set of ternary relations ⊆ × × V and we define the ordering ≤ to hold iff there exists a realising expression ∈ E and potential ∈ 0 such that for all ∈ , ∈ and ∈ V with ( , , ) ∈ , we have that there exists a result ′ ∈ V, step count ∈ N and result potential ∈ with: (1) , ⇓ ′ (evaluation successfully completes in steps); (2) ( , , ′ ) ∈ (the result is well-resourced and satisfies ); and (3) ≤ ( ⊕ , ) (the step count is within the difference between the initial potential and the result potential).
Note that the definition of realisablity is uniform in the element -the realising expression and the potential must work for all -thus the implementation and complexity measure of the transition being modelled cannot depend on what the input is.Put in implementation terms, the input is not present at runtime.Moreover note that the potential attached to the expression must come from the sub-monoid 0 , indicating that is intended to be data-free, while the potential for the input is from the full monoid , so it can contain data and functions.
For , ∈ ( ), the required elements for symmetric monoidal closed structure are defined as follows.For the tensor product ⊗ ∈ ( ), the realising value must be a pair ( 1 , 2 ) and the potential of the pair must split into suitable potentials 1 , 2 for the components.For the residual ⊸ , the realising value must be a closure with potential to, when added to the potential an input, compute the output with enough remaining.Note that the potential attached to a closure ( , here) need not be from the sub-monoid 0 .Unlike top-level term interpretations, closures may contain data.
∃ ′ , , ., ( :: :: The seemingly useless ∈ V in the formula for ⊸ is a dummy argument standing for the self-referential reference to the closure used for defining recursive programs. Each ( ) has a terminal (i.e.top) element, which is also the unit for ⊗, defined as = {( , , * ) | ∈ , ∈ }.The potential here is unrestricted, so can consume an arbitrary resource.N-Graded exponentials in each ( ) are defined using the action of (N, ≤) on defined above.When > 0, the modality ! has no effect on realising values.It only serves to alter the resource potentials.In the = 0, case the realising value must be * , in order to satisfy the !0 condition in Definition 5.5 3(a): also has arbitrary Set-indexed products, realised "lazily" as functions that take dummy arguments.For ∈ Set and ∈ → Set and ∈ (Σ .), we define ∀ ∈ ( ) similarly to ⊸ above, but with different resource and indexing requirements: Note, as with the definition of ≤ above, the realiser closure clo , must be chosen uniformly for all .This definition also appears to allow arbitrary computation (paid for by ) to happen when the realising closure is applied, but the potential will only ever be greater than by enough to handle the administrative costs of applying the function.
To complete the construction of as an indexed linear preorder, we need to give realisers for each of the required inequalities in Definition 5.5.In each case, this is a matter of programming in the language of Section 5.1.For example, transitivity of the order is realised by sequencing of expressions.The potentials are calculated by counting the steps in the ensuing programs.P 5.6., with , ⊗, ⊸, !, and ∀ defined above, is an indexed linear preorder.
Agda Formalisation.The construction of this indexed linear preorder and the proof of Proposition 5.6 are formalised in the Adga module AmortisedRealisabilityModel.

Non-iterable Data
Types.The model of QTT constructed in Proposition 5.6 does not yet include any useful base types.Iterable types, which are the ones that induce non-constant time complexities, require specific properties of resource monoids that we introduce in Section 6.
Before that, we show how to define realisers for the representative examples of non-iterable types from Section 2.2 and Section 3.2.Booleans are the simplest case, with only two cases and no chance of iteration.Lists are more complex: we can have non-iterable lists containing iterable data.
Booleans.Fix B = { , ff } as our set of boolean elements.We define an element of (B) to represent boolean values: Thus, the boolean is represented by the value true and ff is represented by false.In both cases, we allow arbitrary potential to be attached.
Realisability of the construction and elimination of booleans amounts to the existence of the following inequalities.In any preorder ( ), we have ≤ * Bool and ≤ ff * Bool (treating and ff as constant functions → B).These inequalities are realised by the corresponding true/false expression.For conditionals, the types involved are a little more complex to ensure agreement between boolean manipulations at the Set-level and the realising computations.To get a realiser for a conditional, we require a set , an element ∈ ( ) (standing for the context) and an element ∈ ( × B) (standing for the target type) and the existence in ( ) of inequalities ≤ ( .( , )) * , for the true case, and ≤ ( .( , ff )) * , for the false case.When we have all these, we get in ( × B) an inequality * 1 ⊗ * 2 Bool ≤ .This construction suffices to realise the rules for QTT booleans in Section 3.2.
Lists.Lists are a little more involved, due to the need to explicitly manage a context that applies to all elements of the list.Let List( ) be the set of lists with elements from a set .If we have : Set and : → Set and ∈ (Σ : .), then the resourced lists predicate RList( ) ∈ (Σ : .List( )) must satisfy the equation: This equation has a least solution, by induction on the length of the list being realised.This definition is somewhat involved, but in essence states that a list is represented by tagged pairs, where false represents nil and true represents cons, and that the potential is distributed amongst the elements of the list as needed.
Agda Formalisation.The construction of realisers for booleans and lists are carried out in the Agda modules AmortisedModel.Bool and AmortisedModel.List.

REALISING ITERATION FOR IMPLICIT POLYNOMIAL TIME
The models constructed in the previous section only allow for constant-time programs to be realised.To interpret the iterators of the Cons-free and LFPL-style systems, we need to use the MaxPoly and PlusPoly resource monoids.We do this in this section, where first we establish some operations that will be useful to see how they capture the nesting of iterations inherent to polytime computation.

Iteration Resource Monoids
To interpret iteration over a resource monoid ( , 0 ), we require additional structure, which we call an Iteration Resource Monoid to account for measurement of the sizes of iterable data structures and the effects of iteration on potentials.
6.1.1Definition.We require: (1) a function size : N → that gives the potential of an iterable data structure of a given size; (2) a function raise : → that raises the (polynomial) degree of some potential; and (3) a function scale : N × → that scales a potential for a fixed number of iterations.
The first property states that raise is suitable as potential for whole programs, meaning that it does not make any requirements on the existence of iterable data.Note that we do not require 0 to contain size( ) -programs themselves may not contain iterable data, all potential for iteration must be delivered externally.A useful intuition is that scale( , ) represents the potential required for at most iterations that require potential , whereas raise( ) represents the potential required for a number of iterations that depends on the context.This is the motivation behind the second required property, which states that having raise( ) potential implies having scale( , ) potential when the current size is .The third property states that scale decomposes as expected on potentials that do not include any size potential.
Note that scale( , ) is not the same as the action • defined in Section 5.2.The latter operation scales both size and function potential, but the former only scales the function potential.
6.1.3Realising Iterable Natural Numbers.For any natural number , we define its representation as a value natValue( ) ∈ V by recursion: This representation uses a tagged pair approach similar to our representation of lists in Section 5.4.2.Using this, we can define what it means for a natural number to be realisable via Nat ∈ (N): So a natural number is realised by the value natValue( ) as long as we have at least size( + 1) potential (we add one to make the LFPL soundness proof easier).This gives us the ability to represent natural numbers as a type in QTT, but in order to iterate (and construct in the case of LFPL), we need to construct specific realisers for the Cons-free and LFPL systems.

The Cons-Free System
The Cons-free system uses the MaxPoly resource monoid, with the distinguished sub-monoid being those elements that are 0 in the size component.We enumerate the features of the Cons-free system and justify their realisability with the MaxPoly resource monoid: (1) Duplication of natural numbers by dupNat( ) is realisable by the expression (0, 0), which creates a pair by copying the input variable twice.By the cost semantics in Section 5.1, this takes 1 step of computation (we assume that it is actually implemented via some pointer copy).The resource accounting for this realiser works because the size component required for the output is the maximum of the size components of the two elements, and since ⊔ = , we have enough resources to fulfil this.(2) Construction of natural numbers is not realisable.In a putative succ rule, we would need to get an additional unit of size resource from nowhere.
(3) Iteration is realised by constructing a realising expression in the expression language from the given expressions for the zero and successor cases that uses the in-built recursion of the language.The proof that resources are correctly accounted for is carried out by induction on the natural being iterated over.For , we require potential scale( , acct (4) ⊕ succ ) ⊕ (acct (2) ⊕ zero ), where succ and zero are the potentials required by the successor and zero cases respectively.By Property (2) of iteration resource monoids, above, we know that raise(acct (4) ⊕ succ ) ⊕ (acct (2) ⊕ zero ) always dominates this requirement when paired with the potential size( ) from the input.Therefore, this latter expression, plus some administrative set up costs, is the required potential for the whole iterator.Together, we have a soundness result for the Cons-free system, that ensures that every term in the = 1 fragment is realisable by a correct program that terminates in polynomial time for all inputs: Agda Formalisation.The realisability of the Cons-free system iterator and the soundness property of the whole system are formalised in the Agda modules ConsFree and ConsFree.Iterator.The soundness theorem is a combination of this and the QTT model sketched in Section 5.3.

The LFPL System
The LFPL system uses the PlusPoly resource monoid, with the distinguished sub-monoid again being those elements that are 0 in the size component.With this resource monoid, the capabilities offered at the QTT level are altered: (1) We can no longer duplicate natural numbers, because Nat ⊗ Nat requires twice as much size resource as Nat, due to the combining operation on size potentials being addition.(2) We define the realisability specification for diamonds ∈ (1) to be = {( * , , * ) | 0 ≤ ( , size(1))}.Thus, a diamond represents at least one unit of size resource, matching the intuitive explanation given in Section 2.4.
(3) With this definition of realisability for s, it is possible to realise the zero and succ constructors for natural numbers.By the additive combination of size resources we get 1 from the diamond and + 1 from the predecessor to total + 2 for a new number.Note that, even if we add a type to the Cons-free system, it would still not be possible to realise the constructors, because we would only have 1 ⊔ ( + 1) = + 1 size resource for the output.(4) The construction of the recursor follows a very similar proof to the realisability of Cons-free iterator, up to some additional work to make sure that the dummy * values representing the diamond components end up in the right places.This additional work is revealed in the required potential for the LFPL iterator being raise(acct (8) ⊕ succ ) ⊕ (acct (2) ⊕ zero ), so slightly higher in the successor case.
Soundness for the LFPL system is similar to the Cons-free system, except for a +1 to the input to the polynomial, to account for the fact that we cost one size unit for the zero constructor.The proofs of well-accounted realisability for the LFPL iterator, and the Cons-free iterator, could be adapted to any other inductively defined type that is finitely branching.This is not immediately necessary, as evidenced by the construction of other datatypes in Section 4.1.Nevertheless, native tree type where the iterability is proportional to the total number of nodes would be useful.
Agda Formalisation.The realisability of the LFPL system iterator and the soundness property of the whole system are formalised in the Agda modules LFPL and LFPL.Iterator.

RELATED AND FUTURE WORK
We have presented two extensions of Quantitative Type Theory that soundly and completely capture polynomial time.This allows for an expressive combination of verification and complexity constrained computation, including characterisations of the classes P, NP, and BPP.We now discuss related work, and take a look at where the combination of polytime and dependency could take us.

Related Work
Implicit Computational Complexity with Linear Types.Implicit Computational Complexity [Dal Lago 2011] is a vast field, so we only survey closely related works.We have already mentioned the Bounded Linear Logic [Girard et al. 1992], Soft Affine Logic [Lafont 2004], Light Linear Logic [Girard 1998] and LFPL [Hofmann 1999] systems, which all use linear typing to implicitly capture polynomial time.Jones [2001] characterises polynomial time using first-order functional programs without constructors.Thus it shares a method with our Cons-free system, but we use linear typing to permit controlled use of higher-order functions.Other approaches to polynomial time use stratification or information flow tracking to ensure that the outputs of iteration may not be used unrestrictedly to drive further iteration.For example, [Bellantoni and Cook 1992] and [Hainry and Péchoux 2023].Below polynomial time, systems have be devised to capture LOGSPACE [Dal Lago and Schöpp 2016].Above polynomial time, systems such as Elementary Affine Logic (EAL) capture all Elementary-time functions [Coppola and Martini 2001].
We have used Dal Lago and Hofmann [2011]'s technique to prove soundness of our extension of QTT.This technique has been successfully applied to many other linear typing based systems, such as BLL [Dal Lago and Hofmann 2010a;Hofmann and Scott 2004] and LLL [Dal Lago and Hofmann 2010b] and EAL.In contrast to most of those systems, we do not use restricted !-modalities and second order encodings to express datatypes.Our explicit datatype approaches enabled our combination of dependent types and polynomial time.
Explicit Resource Accounting with Dependent Types.In contrast to the implicit systems, previous works have constructed systems that give explicit resource bounds via typing.Examples include Hoffmann et al. [2017]'s Resource Allocated ML (RAML) and Rajani et al. [2021], both of which are based on ideas of type-based amortised complexity analysis arising from Hofmann [1999]'s ideas, via the work of Hofmann and Jost [2003].More details are to be found in the survey paper of Hoffmann and Jost [2022].Another approach is to track costs at the value level instead of the types.Danielsson [2008] describes a system that uses a "tick" effect to count steps of computation, which can be reasoned about via dependent types.Niu et al. [2022] take this idea further by employing a modality-based phase separation to ensure that tick counting never interferes with the functional business of programs.McCarthy et al. [2016] is another tick effect based system in Coq.All of these tick-counting techniques rely on the programmer correctly annotating the program with tick effects to count the resource usage they are interested in, in contrast our intrinsic approach.
Linear and Substructural Dependent Types.We chose QTT as the particular combination of linear and dependent types for our systems.Other systems include systems such as those by Cervesato and Pfenning [2002], Krishnaswami et al. [2015], and Vákár [2014] which all use a strict separation between linear and non-linear variables.This strict separation would mean that we could not as easily move programs from the linear fragment into the types, as in Section 4. Systems that are more like QTT in that they do not have a strict separation of variables include those of Moon et al. [2021], Choudhury et al. [2021], and Abel et al. [2023].These systems differ from QTT in that they do not include a complete copy of unrestricted type theory as QTT does in its = 0 fragment, because they all track usage in types as well as terms, so it is not clear how to use them for unrestricted reasoning as we do with QTT.Fu et al. [2022] present a system that is closer to QTT but does not include a universe type, which we used in Section 4.3 to be able to characterise complexity classes as predicates decidable in restricted complexity.

Future Work
Implementation.We currently lack an implementation of our extension of QTT, which hampers further investigation of programming and proving with polytime along the lines of Section 4. Idris 2 [Brady 2021] is an implementation of QTT, but cannot be used directly because its facility for defining datatypes is too liberal, not making a distinction between iterable and non-iterable datatypes.A further implementation-focused question is whether or not the term-level polytime guarantees can be turned to type-level guarantees to guarantee polytime typechecking.
Other Complexity Classes.We have been able to characterise the classes NP and BPP in terms of our underlying characterisation of P (Section 4.3).It seems straighforward to extend this to related classes like coNP, RP, etc.It also seems feasible to adapt the techniques presented here to other complexity classes such as LOGSPACE and ELEMENTARY, given the simply typed linear systems mentioned above.Complexity classes based on circuits may be more challenging, but we do now have a way to characterise circuits that are generatable in polynomial time.
Explicit Resource Tracking.Our construction already includes soundness of a system with intrinsic but explicit resource tracking where s are used to pay for every step of computation but never returned, via the natural number resource monoid defined in Section 5.2.1.Investigation of such a system may yield a system that tracks the intrinsic cost of programs precisely and explicitly.
Towards a Synthetic Computational Complexity Theory?The realisability type R( ) described in Section 3.5 allows us to internalise the realisability of certain functions into the logical ( = 0) fragment of the calculus.However, it is not possible to derive any logical consequences from this other than turning it back into a function.This limitation becomes acute when trying to prove results from standard Computational Complexity theory.Even though we can characterise the class NP, as we did in Section 4.3.1, and it is a "matter of programming" to show that 3-SAT is in NP, we cannot prove the Cook-Levin theorem that 3-SAT is NP-complete.This is because the proof relies on obtaining the source code of the program solving an NP problem and then encoding that program in 3-SAT.To do this in our setting, we would need to internalise the soundness property (Theorem 6.2) as an axiom, stating that for a realisable polytime function there (merely) exists a realising expression that completes in polynomial time, and then writing polytime encodings into 3-SAT.We hope that the addition of such an axiom to our system would lead to an expressive machine-free Synthetic Computational Complexity Theory, analogous to the Church-Turing axiom for Synthetic Computability Theory as described by Bauer [2005].
A TYPING RULES FOR QTT/CONS-FREE AND QTT/LFPL The judgements of Quantitative Type Theory are as follows: In the term and term equality judgements, the usage is either 0 or 1.We use and to range over arbitrary usages from the semiring .

:
IList ) → Sorted(xs, insertionSort xs) 4.3.2Bounded-error Probabilistic Polynomial Time.By changing the computation effects supplied to a program, we can change the complexity class.To capture the class BPP of Bounded-error Probabilistic Polynomial time [Arora and Barak 2009], we use a (non-iterable) data structure representing trees of probabilistic choices, where Q[0, 1] is some type of (non-iterable) rationals in the closed interval [0, 1]: data Dist ( : U) : U where return : → Dist choice
then there exists a realising expression and polynomial such that for all ∈ N, there exists ∈ V and ∈ N such that , [natValue( )] ⇓ , ≤ ( + 1) and is a realising value for ( ) ∈ ( ).