Manuscript Offprint
arXiv:2610.23023Arbitrary Functors as Modalities in a Linear Calculus
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
We study modalities in the linear lambda calculus, by interpreting them as endofunctors in monoidal closed categories. We support functors that do not distribute over products, including (co)monads. We also support arbitrary natural transformations as conversion between modalities. We provide a generic categorical semantics, which we then specialise to a sound and complete resource semantics. We use this resource semantics to derive normalisation by evaluation. Along the way, we describe several applications of such models. This work aims at providing a foundation for future programming languages with modalities. The paper is backed by a mechanisation in Agda.
1 Introduction
Modalities, rooted in modal logic, provide a formal framework for expressing notions of necessity, possibility, and other modal operators. In programming languages they can be used to model resource usage, concurrency, effects and coefficients, and security constraints [12, 19, 30, 32, 34]. While the term grades is more common in the programming community, we use the word modalities consistently throughout this paper.
Modalities are typically assumed to form a preordered, ring-like structure [2, 9]. Such a structure is sufficiently general to accommodate all of the applications mentioned above, which makes it tempting to unify them within a single system. However, the ring structure imposes (1) distributivity and (2) that modality conversion is computationally irrelevant, i.e. there is a single interpretation of the preorder relation . Our starting observation is that these two assumptions break down when one pushes the generic system to its limits.
Consider first distributivity. As we see below (Lemma 4.4), distributivity corresponds to modalities having the structure of (op)lax monoidal functors; meaning that there are these conversions:

But even commonplace effects such as the writer monad are not lax unless the payload is itself a monoid. Furthermore, if one simultaneously cares about resource usage, the underlying language may be linear, and then even the reader monad is not always lax.
Indeed, laxity of the reader monad requires , which cannot be realised unless is a comonoid; and not all types are comonoids in a linear language.
DRAFT PAPER UNDER REVIEW
Jean-Philippe Bernardy and Andreas Abel
Regarding the second point, assuming that there is a single possible conversion between modalities p and q may be reasonable if there is a single kind of effect, or if they do not interact. [2, 32] This breaks down also if one considers data structures as modalities. In such a case a modality conversion is a reshaping of the structure, and such conversions are not determined by their type.
Our goal is to study type-systems where modalities are not necessarily distributive and where conversion carries computational content.
• not all modalities automatically distribute, and
• modality conversions are made explicit.
(See Section 2 for the precise description of the new modality structure.) Then these relaxations would be applied everywhere in the meta-theory in a straightforward way. However, we found that it is not so simple. Following a standard method of semantic analysis, we found that the calculus must be thoroughly modified in a pervasive way.
In this article, we could just present the final calculus, but we believe that doing so would be less pedagogical, and we prefer to guide the reader through the true path which led us to it. This means that our methodology sometimes departs from a standard description of core calculi. We explain the detours taken in the rest of this section.
First, we define our starting point core language. It is meant to resemble usual calculi with modalities (Section 3). We make the minimal modifications necessary to relax the assumptions that all modalities distribute. We do so by adding side conditions to the rules which would normally just assume distributivity. Unfortunately this calculus does not seem to have the desirable properties. In particular it is unclear how to reduce some redexes.
Rather than extending the syntax haphazardly, we investigate the implications of the design by semantic means. We do so by providing a generic categorical semantics (Section 4); then a (sound and complete) resource semantics based on presheaves (Sections 5 and 7). Along the way, we consider usual and novel applications of modalities and grades, sometimes via the relational model (Section 6) arising from the generic semantics.
Generally, presheaf models can be utilized in normalisation by evaluation techniques: one evaluates the syntax in a presheaf model and then reifies back to syntax. The reification outputs forms which do not context redexes, and are in this sense normal forms. Furthermore, the completeness proof strongly suggests what normal forms one should have. In our case, it provides us with the design of the stable calculus—one with all the desired properties, see Section 8. This final language has the same semantics as the original calculus, but its syntax departs significantly from usual lambda calculi. Our conclusion is that one can not relax modalities to be non-distributive without paying a significant cost in terms of syntactic complications. Yet, we remark that the simplified calculus (the one we started with) appear to be sufficient to describe most applications, even if not all syntactic reasoning can be done using it.
We suggest that the reader eager to see this final version of the calculus does not skip directly to Section 8, but first goes through Sections 2 and 4 and Theorem 7.7.
1.2 Methodological notes
We have completely mechanised our results in the form of an Agda library. Because of the modular structure of the paper, readers may need to navigate between concepts, hence it is heavily hyperlinked, both within the document and to the Agda formalisation. In particular, whenever a checkmark (✓) appears, it links to the corresponding formalisation.
Thanks to its generality and methodology, we hope that this paper will provide a solid foundation for the development of future languages with modalities.
2 The Structure of Modalities
Definition 2.1 (modality structure). ✓ A modality structure is a category augmented with:
• Two monoidal structures: and .
- Proof-relevant predicates and that single out distributive and codistributive modalities. I.e., the propositions and are actually sets containing witnesses of (co)distributivity.
• A distinguished element of and .
To distinguish modality structures we will denote them with a script font. The object set of a modality structure , written , contains the modalities, and the homsets of the above category represents convertibility between modalities. To our knowledge, programming language literature [2, 9, 32] assumes that each such homset has at most one morphism. In other words, modalities form a poset. (See also Section 11.) Even though we do not assume such, it remains an important motivating situation, and hence we write for the set of conversions from to .
Modalities p act on types A via qualification , producing a modal type. The calculus is designed such that the following principles of interaction between modalities and other type formers hold. First, the additive monoid interacts with types like so:
(zero principle)
(sum principle)
Hence the modality 0 corresponds to no use, and corresponds to combined p-use and q-use. Multiplication arises from composition, and is governed by the following principles (in this case, bimaps, unlike the addition principles above):
(unit principle)
(product principle)
The unit qualification is always equivalent to no qualification, and combination behaves multiplicatively. Because qualification also behaves functorially ✓, is always simultaneously a graded monad and a graded co-monad.
(functoriality)
A modality morphism can be lifted to a function:✓
(lift)
To reviewers: to access the formalisation in this way, the extended material must be unpacked so that the html directory resides in the same directory as the PDF file. Additionally, the PDF reader must support local links, as many do not. Google Chrome works on all tested platforms, and Evince works on Linux.
Jean-Philippe Bernardy and Andreas Abel
Most of the literature on modalities posits that (·) distributes over (+), and then distributes over products. As mentioned in the introduction, we will not make this assumption in general, and restrict distributivity to the modalities which satisfy or , like so:
(factorisation)
(distribution)
The purpose of and is to carry the computational content associated with the above types. When modalities from a poset, and are just conditions. The articulation between those sets (or conditions) and distributivity is explained in detail in Section 4.
3 Lambda Calculus with General Modalities
In this section we introduce , a typed lambda calculus augmented with modalities in . It is designed as a minimal extension of modern lambda-calculi [2, 33] with modalities, to support non-distributive modalities and explicit modality conversions. The calculus can also be considered as a modal (linear) logic. For most of the paper, we only consider simple types, but discuss polymorphism in Section 11.
Types are given by the following grammar.✓
The letter ranges over a set of base types. These types will be used in the semantics to freely interpret type variables beyond the types formed from 1, &, , , and , which have a fixed meaning. Base types are generic unless equipped with primitive operations. We have two product types (multiplicative) and (additive), and they behave as in linear logic. Namely, eliminating requires consuming both and , whereas only allows either or to be consumed. The function type is purely linear, and is the qualification of by an arbitrary modality .
Consequently, is a calculus for substructural typing [38]. The availability of structural rules is precisely controlled by modalities. There is no sum type, but bits of information can be exchanged using the type , for some suitable continuation type . In general, we can define . In the presence of polymorphism we can even define , which is isomorphic to the usual sum type.
Contexts. In contexts, variable bindings are annotated with a modality:✓
We can scale contexts by a modality q, pointwise:✓
Thus contexts are a free module generated by simple bindings of form .
Terms
Patterns
Fig. 1. Typing rules of . The judgement is for terms and is for patterns.
Terms and typing. Our syntax follows that of typed usual lambda calculus with patterns:
But we allow pattern bindings in let and abstraction. Patterns admit the following syntax:
The typing judgement has the form , meaning that has type (with an implicit modality 1) in context . A variable occurrence always corresponds to usage 1. This ensures stability of usage under variable substitution. In the rest of the paper, any omitted modality annotation defaults to 1. The pattern typing judgement means that with modality , the pattern analyses the type into the variable bindings .
The typing rules are shown in Fig. 1. A number of points are worth detailing. First, while the eliminators of are usual projections, the elimination of , 1 and is done by combining let with patterns (respectively , () and ). We also allow pattern binding in -abstraction for convenience. All listed patterns accommodate arbitrary modalities, though and () impose side conditions, yielding the restriction of distribution. Meanwhile, the pattern sustains the product principle in the left-to-right direction.
Jean-Philippe Bernardy and Andreas Abel
zero principle
sum principle
unit principle, left to right
unit principle, right to left
product principle, left to right
product principle, right to left
distribution, unit
factorisation, unit
distribution, pair, given
factorisation, pair, given
lift
functoriality
Fig. 2. Implementation of the principles relating modality qualification and other type formers.
Second, several patterns handle modalities specifically, instead of type constructors. The pattern applies the morphism to adjust the modality of a pattern, sustaining lift. The pattern matches any type with modality 0 without binding variables, sustaining zero principle. Finally, matches a type with modality by decomposing it into (matching modality ) and (matching modality ), thereby supporting sum principle.
Finally, -INTRO requires either a singleton context or an element of . Accordingly, functionality has no side condition, while factorisation has one. A detailed semantic analysis of these conditions follows in the next section. Figure 2 shows the lambda terms for each principle, demonstrating the purpose of patterns.
3.1 Issues with Operational Semantics
We arrived at the above syntax by making minimal changes to earlier calculi to support non-distributive modalities. Specifically, we conditioned some rules with and as needed and extended the pattern syntax for explicit conversions and explicit handling of modality sums. This change allows us to support the desired programming principles (Fig. 2) in a convenient way.
However, is not stable under computation: comprehensive extensions to pattern bindings are required. The usual approach is to define how eliminator patterns reduce with the corresponding construction. For instance, for products, the binding reduces to two parallel bindings: and . For , the binding would reduce to a -way pattern . This already complicates bindings beyond syntax. We could extend the syntax to support this form, but there are further complications because of the modality-transformation patterns and , which do not interact with the type-structure. For instance, we could have bindings such as . It is clear that the pattern syntax must be further extended to reduce this binding form, but it is unclear at this stage how exactly.
Instead of trying to complete the calculus in a ad-hoc way, we will derive the final form of patterns, using semantic means (Section 8). The first step is to define a categorical semantics for .
4 Categorical Semantics
Let us, for the sake of presentation, consider a simplified version of without modalities—effectively assuming that every modality is 1. This yields a purely linear language. The semantics of this restricted language naturally aligns with a symmetric monoidal closed category equipped with finite products, which we denote as .
Definition 4.1 (SMC ). ✓ A SMC is a category C augmented with:
• A symmetric monoidal structure .
-
Finite products (&, T). In contrast to the product, it has projections and and pairing . This product is in general distinct from the product.
-
Internal hom-sets , such that . Note that these are adjoint to the product, not the product.
Standard coherence conditions apply. The and products are independent, but if they coincide the category is Cartesian closed. We overload the notation for types and their interpretation, using color to distinguish them.
The notation that we use the morphisms of a SMC is as follows. For the monoid structure:
• If and then
For finite products (&, T):
• and
• if and then .
•
The isomorphism is witnessed by:
• app:
• if then
Modalities are interpreted as endofunctors on C. Crucially, the collection of such endofunctors forms a modality structure.
Definition 4.2 (endofunctor modalities). ✓ Let be the modality structure defined by:
endofunctors
natural transformations between those
corresponding functor composition
identity functor
pointwise monoidal product
constant functor (map every object to the unit)
(see Def. 4.3)
Remarkably, there is no restriction on the chosen functors or the chosen natural transformations. Indeed, the modality structure arises from already assumed structures:
Jean-Philippe Bernardy and Andreas Abel
• Its category structure is provided by the category structure of natural transformations.
- The monoidal product is given by the monoid of endofunctor composition .
• The monoidal product is given by the monoidal product structure .
As we detail in the rest of the section, the choice of and is exactly that which is required to interpret , but it is also one which corresponds to distributivity laws. Let us first review the definitions.
Definition 4.3 (lax and oplax functors). A functor is lax ✓ if there are natural morphisms and . Conversely, it is oplax ✓ if we have natural morphisms and . The definition of lax and oplax functors come with a number of additional coherence laws, but they are orthogonal to our development.
LEMMA 4.4. In , the sets and (by definition witnessing laxity and op-laxity) are in bijection with (natural) distributivity homsets for modalities:
The above lemma is of practical interest to the programmer, because one can characterise and syntactically, in terms of the modality structure, rather than semantically.
We have all pieces in place and thus can proceed with the interpretation of .
THEOREM 4.5. For any C and a map of base types into objects of C, there is an interpretation of into C.✓
PROOF. The product is used to interpret types, but also context concatenation. As usual, every type is interpreted as an object and every context is interpreted as an object , relying on the monoidal structure to interpret concatenation of contexts: and . Modalities being endofunctors, one can interpret qualified types as and modalities in contexts as . The judgement is interpreted as a morphism , and a pattern is interpreted as a morphism . The object is used to interpret function types; and product objects interpret product types.
The choice of the functional interpretation of the monoid is just the one needed to make the interpretation of and . The pattern is interpreted to .
The interpretation of -INTRO relies on using the functional action of on the interpretation of the premise. Additionally, the interpretations of the hypotheses must be grouped together as . This can be done thanks to being lax, via the condition when isn't a singleton; otherwise no operation is required.
Additionally, pattern matching a p-qualified pair (resp. unit) is possible under the condition that p is oplax, and this is given exactly by the side conditions.
We can summarise the semantics as follows. First, the semantics of terms is given by:
Where is the context of the term.
The (silent) context re-orderings are interpreted using the monoidal structure, and the semantics of patterns is the following:
In the above if we let and be the morphisms witnessing the laxity of functors, and in general collects objects under the functor. Then is the identity. The notation refers to oplaxity witnesses.
The semantics of modalities in terms of endofunctors is quite general: one can pick any SMC , and then any endofunctor is available as a modality. This is useful, but this level of generality restricts the (meta)theoretical results that one can obtain about the calculus. Therefore, most actual applications do not to expose arbitrary functors as modalities, but only a substructure. Yet, our guiding idea is that every useful modality structure can be mapped to the functorial one. This idea is illustrated throughout the paper with a number of examples. To formalise it, we first need the notion of homomorphism between modality structures.
Definition 4.6 (modality functor). ✓ A modality functor is a functor between the underlying category structures of and which
• weakly respects the monoid (oplax functor wrt. )
• strongly respects the monoid (strong monoidal functor wrt. )
• respects the and families
This implies that we have the following natural morphisms, natural isomorphisms and functions:
Jean-Philippe Bernardy and Andreas Abel
Note that the operations and conditions on the right-hand sides refer to the modality structure G.
REMARK 1. ✓ Any modality functor gives rise to a map from to . This map applies to types, contexts, terms and patterns; and preserves typing.
COROLLARY 4.7 (CATEGORICAL SEMANTICS). ✓ Given a modality functor and a map we can interpret in a SMC, & C.
PROOF. First we apply the modality functor on the terms of the calculus. Then we interpret terms using Theorem 4.5.
It can be enlightening to consider what a homomorphism entails. Note that there are two levels of functors here: endofunctors in , and a functor from to those. So, we have a map from to -endofunctors, which respects several conditions. First, we must have the following natural transformations:
Second, from (resp. ) one must be able to construct a lax (resp. oplax) structure for The rest of the paper provides several applications, in the form of specialised modality structures, and their morphisms to .
4.1 Example: Forgetful Modality Functor
A simple but important modality functor is the one which forgets all modalities. Consider the trivial modality structure , given by choosing (a set with a single element, implying ). Then, is a usual lambda calculus with cartesian product types. In this situation, the categorical semantics reduces to the usual semantics of the lambda calculus in terms of cartesian-closed categories.
THEOREM 4.8 (SEMANTICS OF ). ✓ If C has cartesian products, there is a modality functor , given by mapping to the identity functor . The additive laws and ) are satisfied, thanks to an argument similar to Remark 4. The rest of the conditions demanded by Definition 4.6 are trivially satisfied.
REMARK 2. For every , there is a homomorphism . Consequently, one can erase modalities from any instance, and obtain a usual lambda calculus.
4.2 Application: Arrays
A first non-trivial application is arrays with known sizes (natural numbers). We let modalities be the sizes of arrays, such that is interpreted as an array of A of size . In this application the product principle, corresponds to flattening and unflattening of arrays. corresponds to array split. In general, bare is not sufficient to program all useful array programs. Primitives such as sum : or concatenation are also needed. (For this last case, see also Section 10.) However, -INTRO and the corresponding pattern lets us map, zip and unzip arrays conveniently. Here is for instance the dot product of two N arrays of length , given mul : :
Semantics. Thanks to the groundwork layed out above, to provide semantics we only need to specify the modality structure and a modality functor .
Definition 4.9 (N). ✓ We can enthuse the natural numbers with a modality structure by leveraging the usual the additive and multiplicative structures. The convertibility relation ( ) is just equality. We assert that all arrays sizes can be (un)zipped by letting , be a unit set.
Definition 4.10. ✓ Let be an endofunctor which maps A to the n-ary product of A:
THEOREM 4.11. a is a modality functor . ✓
PROOF. All the cases (in particular, that is both lax and oplax) are either immediate or can be proved by induction on .
We stress that in , copies of data must be made explicit. In this instance, this means that the management of the memory associated with arrays is explicit. This instance of does not keep track of structured array shapes (for “tensors”). To support such shapes, one could make modalities be expressions of a language with explicit sums and products (×). Operations like transpositions would then be provided as modality morphisms, such as .
4.3 Application: Sensitivity Analysis
Another application is differential privacy, where one is interested in publishing statistically anonymised data without revealing individual secrets. For this purpose, Reed and Pierce [35] present a system which ensures that if a certain amount of noise is introduced in the inputs of a program, then at least the same amount is present in the outputs. In their system, every type A comes with a metric , where denotes the set of non-negative reals augmented with positive infinity. Then a function from to is defined to be -sensitive if it does not increase distances by a factor greater than as defined by the metrics for and : . Consequently, under the assumption that distance 0 means equality at all types, 0-sensitive functions are necessarily constant. Conversely -sensitive functions impose no restriction on the argument. Because of the inequality, -sensitivity is subject to subsumption: if and is -sensitive then is also -sensitive.
We can frame this system as an instance of , and by making c-sensitivity an appropriate family of endofunctors. We first define the underlying category, following de Amorim et al. [15].
Definition 4.12. ✓ Let S be the SMC of metric spaces and 1-sensitive functions. To be precise, each object A is a carrier set associated with a metric and the homset is comprised of functions together with a guarantee that for all . The main non-trivial choice is that of which metric to assign to function spaces. Following Reed and Pierce, we let the distance between two functions be . The carrier set of both
Jean-Philippe Bernardy and Andreas Abel
and is the cartesian product of and , and the associated distances are
For & it is adequate to use the maximum (rather than the sum) because only one of the components of the pair can ever be used.
Definition 4.13. Let be the modality structure with , with the usual arithmetic operations. The modality structure is a preorder rather than a general category and the preorder relation is the opposite of the usual order on : . The sets and are trivial, meaning that one can analyse products and regardless of modalities in the context.
Definition 4.14 (magnifying functor). ✓ Let be a family of endofunctors over which leave the underlying set unchanged and multiplies the metric by the factor , so .
Note that “squashes” A by identifying all of its values.
THEOREM 4.15. s is a modality functor . ✓
Then is a calculus for sensitivity. Reed and Pierce use logical relations to show that their functions satisfy the intended semantics, but we do not need this additionally machinery for . Instead, the standard categorical semantics provides us with the witnesses that any function of type inhabits the interpretation of its type, which in turns guarantees -sensitivity.
In , the principle means that values of squashed types can be ignored, while lets one spread sensitivity across several copies of a variable. The multiplicative and functional principles are unsurprising, but lift gives that whenever , we have . This behaviour is adequate to capture sensitivity as intended.
In the system of Reed and Pierce, there are native coproducts, and one can analyse type variables of arbitrary non-zero sensitivity levels, essentially sustaining the principle
assuming our encoding of coproducts, this is simply
In general, does not admit this principle. However, sensitivity analysis is special, because non-zero magnification commutes with object constructors:
LEMMA 4.16. Let for some . Then:
(1)
(2)
COROLLARY 4.17. Let for some . Then we have a morphism .
Because we have not integrated polymorphism in , we cannot derive (1), but we can approximate it as in the above corollary. If we had polymorphism, we could see that p also commutes with universal quantification, and obtain
Because , there is an inverse magnifying functor , and substituting by provides a semantic justification for (1) in the case of sensitivity analysis.
4.4 Monadic Effects
Because supports arbitrary endofunctors as modalities, it can also support monads as such, and consequently it can be used as a calculus for effects. In this section we consider how using it in this way plays out. The monadic structure can be captured directly in terms of conditions imposed on modalities:
Definition 4.18.
• A modality is a monoid iff we have and with the usual laws.
• A modality is an effect if it is a monoid and we have .
In usual functional programming languages, such monads (monoids in the category of endofunctors) are strong, and thus are also automatically lax monoidal functors—aka. applicative functors or idioms [28]. This lets one sequence effects.
In our setting of monoidal categories, monads are rarely strong. This is why we require for any effect modalities, i.e., demand them to be lax functors at the semantic level. (Laxity is just what is needed to make the monads strong. [26]) There are some important monads in non-cartesian categories. For instance, linear state is a monad in every monoidal category, but not a strong one.✓
This sets up the familiar monadic situation: qualification by means that -effects are associated with a value. As usual, to use a -qualified variable we must account for the effects associated with it, typically by forwarding them to another -qualified value; and this is ensured by rules.
Sequencing effects is achieved syntactically by -INTRO. Its semantics is given by combining effects in the context, using the fact that interprets to a lax functor; thanks to the side condition. Indeed the associated morphism sequences the effects associated with and into effects associated with . Thus the -INTRO rule is similar in spirit to the idiom brackets of McBride and Paterson [28], but the ordering of effects is not determined by the box contents but rather the order of variables in the context . While unusual, this strategy will not cause surprises to the programmer, because the semantics only use when the program explicitly demands variable reordering. At a syntactic level, a substitution procedure would never reorder variables in the context.
REMARK 3. Here modalities must form a proper category rather than just a poset, since contains computational content. For instance, we need to distinguish the two principal ways to form the natural transformation , which are and . In particular for the list monad, where is the list concatenation, those produce different results: the first outer concatenation, and the second inner concatenation.
While it is clear that we have all the components necessary to properly support monadic effects, how convenient it is to use depends on the actual surface syntax. With just , the monadic bind is noisy, and explicitly references and :✓
Jean-Philippe Bernardy and Andreas Abel
The existence of bind means that can be extended with a Haskell-like do-notation. But one can also consider programming using syntax directly. In first approximation, one would replace each monadic bind by a let binding like the above. For instance:
However, there is a subtlety when effectful functions return the unit type. For example, let us consider , the monad threading a linear state of type and the constants get : and put : , using increment inc : and constant 42 : . ✓
In the above, one must retain the effects of put in the variable . It must then be explicitly consumed before returning the final value. This ensures that no effect is lost. Note that the typesystem would not accept consuming outside of a bracket, because we don’t have . Indeed, given we could drop any -effect, which is unsound in general.
In closing, note that + is not all that useful on effect modalities: it represents that either effect can be present (but not both). Yet, knowing that a given effect distributes on addition of other modalities still corresponds to the effect being a lax functor.
4.5 Dual Modalities: Adjoint Functors
A common pattern are dual modalities —not a surprising fact given that they correspond to the common adjoint functor pattern. In the presence of dual modalities, one can present some key rules in a way which is better from a type-checking point of view.
Definition 4.19. The modality is left-dual to iff we have morphisms and such that .
The following theorem is reminiscent of Fitch-style modalities [10]. However, since our modalities are not all (co)distributive, we only recover the adjoint with side conditions: either the context is a singleton or the modality comes with the required (co)distributivity property.
THEOREM 4.20. If has a left-dual, then the following -INTRO rule is equivalent to -INTRO and has an inverse -ELIM:
PROOF. Interderivability of -INTRO and -INTRO is mediated by whole context conversions. In general if then we can apply the pattern to each variable in in the context. Hence the following rule, for whole-context conversion, is admissible:
Then we can define box t and unbox t as follows:
✓
✓
The -INTRO rule can be recovered this way: ✓ The typing derivations are found in Appendix A.1.
Assuming that we have , then the rule -INTRO is invertible and does not constrain the form of when read backwards. Thus, it in such a situation it is safely applicable when deriving . So, if a left-dual is available and , -INTRO should be exposed to the users of the language.
Dual modalities are commonplace: every pair of adjoint functors can work as dual modalities. However, they are not often both lax and oplax functors—and this fact is one of the reasons why we have explicit modality classification through and . Yet, when is lax, is oplax, and vice-versa.
There are several ways to gain intuitive understanding for dual modalities. One understanding stems from the observation that the -qualified variables from the context are inaccessible, so they might just as well be discarded unless their type is p-qualified. That is to say, multiplication of a context by filters out variables which are not p-qualified.
In programming, the paradigmatic example of adjoints is that of currying and uncurrying: the functor is left-adjoint to . ✓ The effect corresponds to using , and corresponds to providing . Furthermore, if is a comonoid (which it will always be if has cartesian products), then is lax ✓ and is oplax; ✓ thus, they are made available to the rules which require and .
In general, if is associated to an effect, then is associated to the corresponding co-effect. Then, the -ELIM rule means that, instead of dealing with effect , one can instead demand a context which provides the coefficient .
4.6 Coeffects
One can use to work with comonadic co-effects instead of monadic effects. As expected, the definitions are dual:
Definition 4.21.
- A modality is a comonoid iff it has and , satisfying the usual laws.
• A modality is a co-effect if it is a comonoid and we have .
We can adapt our example from Section 4.4 to co-effects. Throughout this subsection, we assume to be left adjoint to the state monad. Then it is also a comonad and an oplax functor. Hence one can use -ELIM to obtain the following co-primitives: coget : and coput :
In this style, values of type act as a coefficient source (or equivalently an effect sink). Each effectful function must take one such argument. Thus the program that increments the state and then returns 42 has type and becomes:
This construction is more direct than the monadic equivalent, suggesting that the syntax is better suited to this style. Effects from several functions can be sequenced by duplicating
This left-adjoint is not the costate monad, and does not exist in most categories. To be able to interpret the whole program, it must to be (mechanically) translated back to monadic style. Hinze [22] provides a pedagogical exposition.
Jean-Philippe Bernardy and Andreas Abel
effect sinks, which is possible because (costate is oplax):
The effects will be sequenced in the left-to-right order of the tuple. This kind of control is afforded by linearity: without it, effect sinks could be duplicated structurally, and the sequencing order would have to be specified by ad-hoc syntactic means.
5 Resource Semantics (Kripke Model and Phase Semantics)
In this subsection, we define a semantics for which predicts when a given resource produces (values of) a given type, as an instance of the categorical semantics. This semantics combines aspects of the phase semantics of linear logic [18], and aspects of intuitionistic Kripke semantics. The model is parameterised over an arbitrary structure of resources. What we call a resource corresponds to a world in the Kripke semantics terminology, and a phase in the linear logic literature.
Definition 5.1 (resource structure). ✓ A resource structure is a set W equipped with a preorder ≤ and a commutative monoid which respects the preorder.
The motivating reading is that the resource 0 corresponds to no resource at all; (+) corresponds to resource concatenation; and means that can be transformed to without leftover (so both insufficient or excessive resources may prevent from holding). The preorder can also sustain to model that can be discarded, or to model that can be duplicated.
We then proceed and define a relation between resources and types: . In plain Kripke semantics means that A holds at world w, but for us denotes that a value of type A can be produced from the resource w.
Instead of defining the relation directly we will get it as an instance of the categorical semantics for types, thanks to an adequate structure, called hereafter . We let objects be sets of resources, as is usually done in phase semantics, and define . Additionally, resource sets will always be closed downwards, meaning that if then . This property ensures that any valid resource transformation preserves the predicate.
Definition 5.2 (category of resource sets, ). ✓ Downward-closed resource sets form a . A morphism witnesses inclusion , or equivalently . Object formers are:
The unit object (2) is constructed from nothing; i.e. the resource 0, or any resource that can be transformed to 0. The product (3) breaks down the resources w used for the construction of the pair into resources for the first component and for the second component. This is expressed by the condition . The product can be constructed if both A and B can be constructed. The resources associated with the components are the same as for the whole, because one can only extract either component, never both. The object can be constructed from anything. Intuitively it acts like a garbage bin where one can throw any resource.
The definition of the internal hom (6) states that a function can be constructed from resources w if for any argument that brings its own resources the function result can be constructed with resources . Read differently, the resources for a function application is the composition of the resources for both function and argument. Functions stemming from closed terms do not need own resources, thus, they start with 0, but as a curried function is applied to its arguments one after another, it accumulates the resources coming with each argument to eventually construct a result from all the gathered resources.
To represent modalities, we need a notion of resource scaling. In general, we want resources to form a module-like structure with modalities as scalars.
Definition 5.3 (modality-resource module). ✓ In addition to a resource structure, a modality-resource module is given by
• An arbitrary modality structure Q,
- A resource-scaling operation ((⊠): ) such that the following laws hold:
provided
(13)
provided
(14)
Then, the resource semantics of a modality is given by the following homomorphism from to endofunctors in . The idea is that, to be able to produce with resources , one divides in equal parts such that each part produces .
Definition 5.4. ✓ For , we define the functor acting on resource sets as follows:
The action of on morphisms maps to .
THEOREM 5.5. is a modality functor .
Proof. The proof relies on the distributivity properties of . ✓
COROLLARY 5.6 (SOUNDNESS OF RESOURCE SEMANTICS). ✓ Assume a map from base types to the set of resources which produce it. Then for any modality structure , and any term of , we have .
Jean-Philippe Bernardy and Andreas Abel
PROOF. We use the categorical semantics on to interpret , letting interpret base types and interpret modalities, leveraging the fact that it is a modality functor. We get , or equivalently . We conclude by letting be 0.
Example: multiset resources. Resources can be generated freely from a set of elementary resources. Then a resource is a multiset , addition is the multiset union and 0 is empty multiset. Linearity is then modeled by letting be equality. To sustain affinity for a given elementary resource , one can add .
Typically, modalities would be natural numbers, scaling each elementary resource and preserving the ≤ relation. If one makes a (perhaps frugal) meal with 5 carrots (5 carrot ≤ meal), then one can make two meals with ten carrots: 10 carrot ≤ 2 meal.
However, multisets are N-linear combinations of elements of , thus one can let modalities be N-linear maps on such multisets (). Indeed, as scalars these maps satisfy the laws of a modality-resource module. Running with our vegetable garden example, one can define a season-shifting modality Season, as a linear operator which maps one seed to one carrot. Definition 5.4 effectively computes the inverse of such linear operators, so . Then one can make the same meal from just seeds, but a season later: 5seed Meal.
(It is easy to see how such a setup can be applied to vector spaces and linear transformations.)
5.1 Informational modalities
Even though we have motivated our Kripke-style semantics by a resource analogy, it also applies to resources which are both discardable and duplicable. We begin by characterizing the situation in terms of modality conversions.
Definition 5.7 (informational modality). A modality p is:
discardable iff we have .
duplicable iff we have .
informational iff it is both discardable and duplicable.
Thanks to the use of the (resp. ) pattern, one can discard (resp. duplicate) a p-qualified variable x if p is discardable or duplicable, and an informational variable can be used as many times as one wants. Consequently p is not used to control how much variables are used, but rather in which context they are used.
We say that the modality structure , and by extension , is informational if every modality in is informational.
REMARK 4. If the monoids (C, &, ⊥) and (C, ⊗, 1) coincide, then every endofunctor F in is an informational modality in , i.e., discardable ✓ and duplicable. ✓ In other words, when constructing a modality functor , the and conversions in can always be realised, thanks to the cartesian structure of C.
REMARK 5. In a informational system, the modality preorder is a semi-lattice, with 0 being the top and the meet . That is, for all ,
•
• iff .
We can then define a modality structure from informational modalities.
Definition 5.8 (semi-lattice resources). ✓
A consequence of this choice of resources is that the tensor and cartesian products coincide. Indeed, and because and are downwards closed, . With the same line of argumentation, we also find and
thereby recovering the usual intuitionistic Kripke semantics
Definition 5.9 (lattice modalities). ✓ Given any lattice , we can construct , the structure of lattice modalities, as follows:
Because is a ring, it is clear that is a module with itself as scalars and as operation. ✓ As such, is an appropriate instance of a resource structure, and together with the associated modalities we have a modality-resource module. Then, the main principles become:
zero principle
sum principle
unit principle
product principle
Namely, at resource one has access to both data available at and at ; and at resource one only have access to data which is accessible simultaneously at and at . As for every instance, information flow is determined by , according to lift. The elements of the lattice can be enthused with various intuitions, depending on the application. For instance, they can represent:
• Lamport clocks for distributed computing;
• Agents, and means that agent p believes A;
• Security levels, and means that agent p can access A.
We give a more detailed semantics for lattices with information flow in Section 6.1.
6 Relational Semantics
While the Kripke-style semantics described in Section 5 is effective to determine if some resource can produce some type, in programming languages applications it is often useful to simultaneously establish relations between programs.
In this section we extend Kripke predicates to indexed logical relations. This extension remains a instance of the generic category semantics. The idea is to have two forgetful interpretations (as in Section 4.1) in the category Set, and capture the meaning of modalities by a resource-indexed relation between them. Thus, in this interpretation, an object is a triple of two sets , , and a family of contravariant resource-indexed relations in . More explicitly, resources related by ( ) yield (inversely) contained relations: w \leq w' \to A_{\mathcal{R}}^w' \subseteq A_{\mathcal{R}}^w.
Jean-Philippe Bernardy and Andreas Abel
Definition 6.1 (category of indexed relations). ✓ Contravariant relations form a SMC , & R. The relational components of the object formers are defined as follows:
A morphism in the homset is constituted of a pair of functions and , and a witness that they are related at resource .
The extension of the simple Kripke-style model to relations is oblivious to the related elements. We have asserted in Section 4 that modalities are interpreted as endofunctors. Unfortunately, in the special case of relations, arbitrary functors do not yield the desired models. Indeed, the index-wise product functor is problematic as an interpretation of the modality addition . It comes down the fact that the interpretation of the points must be pairs, but useful relational models assume that when qualifying a type by , the underlying values are not pairs (as they were in the arrays example), but rather two aliases of the same object.
Consequently, we must construct a new modality structure , restricted to relational endofunctors whose underlying functors (in the Set category) are the identity functors. ✓ (Hereafter we refer to this kind of functors as identity-endofunctors.) Such functors are characterized by:
- A map between contravariant relations. If the input relation family is noted , then the constructed family is noted .
• An action on morphims in R.
The functional action on these morphisms is a proof that functions remain related under the action on morphisms. Namely: . ✓ We proceed to define a new product of objects in whose purpose is to interpret modality addition:
In contrast to the 1 and relations formers, the and relation formers are defined for any underlying domain, not just the product in Set. Coincidentally, the same underlying values are related by both operands of . Defining pointwise identity-endofunctors for is impossible, but not a problem for .
Definition 6.2 (modality structure of identity-endofunctors). This structure, called , is:✓
identity-endofunctors
natural transformations
functor composition
identity functor
pointwise application of
Note that the distributivity conditions continue to refer to (op) laxity wrt. to the monoid, not . Indeed, distribution and factorisation are about splitting and joining data, whereas has the same data on both sides. Hence Lemma 4.4 does not apply for relational semantics. Regardless, is usable on identity-endofunctors, because they embed into relational functors.
THEOREM 6.3. The embedding is a modality functor.✓
PROOF. Most of the cases are immediate, but the structures differ for sums, and thus we have to show that we have natural transformations and . The underlying natural transformations are discard ( ) and duplication ( ), from the cartesian structure of Set. But in fact, at the relational level, there is by definition no difference between and (and respectively and ) when the underlying transformations are (respectively ).
We are now done with our generic relational interpretation for modalities in . Because modality functors compose, it means that to instantiate this generic relational model on any new modality structure , we need only a modality functor . We show an example in Section 6.1.
With the category of indexed relations, the categorical semantics specialise to the fundamental lemma of logical relations:
THEOREM 6.4 (FUNDAMENTAL LEMMA). ✓ Given , a resource and two environments and related by we have .
To clarify, for every binding in context , the components of the respective environments are related when .
6.1 Application: Information-Flow Security and Non-Interference
One application of modal type systems is to ensure that certain parts of a program do not have access to private (high security) information. Several type systems have been proposed to explicitly support this feature, notably the seminal work of Abadi et al. [1].
We have seen in Section 5.1 that lattice modalities model a flow of information in the ( ) direction. In the information-flow community, this property is expressed as non-interference, namely that the public output of a program does not depend on secret inputs. To prove this property for , we need to instantiate the relational model appropriately for informational modalities.
Jean-Philippe Bernardy and Andreas Abel
Before proceeding, we can spend some effort checking that the category of indexed relations provides the right definition for our application. Recalling that each resource stands for a security level, the relation will identify values of type A that an agent of clearing level is not allowed to distinguish (“see”). One extreme is the discrete relation that hides nothing and allows one to distinguish everything (full information); the other extreme is the full relation that identifies any two values and thus hides everything (no information).
Because security resource-levels form a lattice, the product structures (&, T and ⊗, 1) coincide, and our relational semantics reduces to the usual Kripke logical relations.
In particular, the empty tuple is indistinguishable from itself; and accordingly the corresponding semantic relation may hold at all security levels, as there is never a need to look into the empty tuple, regardless the capabilities an agent is equipped with. Likewise, the capability to access a pair should include the capability to access both components. Turning this statement around, a pair is only indistinguishable from another pair if both respective components are so. Because resource-levels form a lattice, in Eq. (16) is the meet , and the condition breaks down into the pair of conditions and .
From the security perspective, access to a function and access to its argument should be sufficient to get access to the result. Thus in Eq. (19) setting the resource of the result to , does the correct thing for access control to functions.
We now proceed to map lattice modalities (L) to identity-endofunctors. Following Algehed and Bernardy [4], we provide an identity-endofunctor which hides the information below a given level.
Definition 6.5 (hiding functor). ✓ For each security level we define the functor whose action on contravariant relations is: .
We can see that if the premise is false, and thus the whole relation is trivial: and can no longer be distinguished, or “hidden”. Otherwise, and the relation remains the same. Taking the dual viewpoint, the higher the clearing level , the more one is allowed to see, thus, the fewer values become related by the indistinguishability relations. This matches the fact that relations are contravariant: implies A_{\mathcal{R}}^w' \subseteq A_{\mathcal{R}}^w. This observation is the key justification for being a suitable modality functor:
THEOREM 6.6. s is a modality functor .
We have now all the pieces to obtain non-interference for , which states formally that if a level is more private than , then an input protected at cannot influence an output at .
THEOREM 6.7 (NON-INTERFERENCE). ✓ If , and , and , and then .
PROOF. The proof is an application of the Fundamental Lemma at resource-level , and essentially relies on the definition of the modality functor s. Because the inputs are at a higher level l, they are not observable and thus always related. Because outputs are at the default level (that for which we use the Fundamental Lemma) the output relation is the standard one for booleans (simple equality).
□
7 Computationally-Tracking Resource Semantics (Presheaf Model)
The model of Section 5 does not account for what happens in the (co)effectful models, because it ignores the computational content associated with resource conversion. In this section we amend it to account for computational effects.
First, the resource structure must be a category rather than a set:
Definition 7.1 (resource structure). ✓ A resource structure is a category W, with as hom-sets, equipped with the symmetric monoidal structure .
The homset is a proof-relevant version of the predicate used in the plain Kripke semantics. The laws required by the modality-resource module structure are thus witnessed by morphisms in the category of resources, which are also required to be natural.✓
Second, the target category is one of presheaves rather than just downward-closed sets. In fact a downward-closed set is exactly a contravariant functor from the preordered set W to Prop, and a presheaf is a contravariant functor from the category W to Set. Thus for each type A, we have a functor that maps each resource w to a set of values. Each value is a witness that w produce A. In particular, a value may contain explicit reference to resource transformations. The presheaf action on a conversion turns any value into an element of . Following Scott [37], we write for this action. As any functional action, it must respect identity and composition .
Definition 7.2 (category of presheaves over resources). Presheaves over a resource category W form a SMC , hereafter called . The action of object formers on resources are:
Most cases extend the non computationally-tracking variant straightforwardly, but deserves a commentary. It is the Day convolution of the presheaves and . It is similar to the set , but with an additional naturality condition, expressed by using a coend instead of an existential. What is this additional condition? Consider two triples and inhabiting the above set. We want to consider them equal when, for any conversions such that and we have . That is, it does not matter if we convert by and separately in the components or by as part of the resource splitting.
In the category, morphisms are trivial, but not in . Hence we must check that they satisfy the laws of , and that they respect naturality in resources: for every morphism we have . The proofs are sometimes tedious, but machine-checked. ✓
Third, the resource-scaling functor family must be amended in a similar manner to the product.
Jean-Philippe Bernardy and Andreas Abel
Definition 7.3. ✓ For any modality in , . It is the left Kan extension of along .
A payoff of this model is that the soundness of resource semantics now becomes an evaluator:
COROLLARY 7.4 (EVALUATION). ✓ Assume a map from base types to resource presheaves. Then for any modality structure , we can evaluate a closed term of to a value in .
7.1 Example: Parallel Execution Time
Let us now considering time as a resource. We let the resource structure be the positive real numbers, and use maximum as a monoid, yielding an informational modality set:
Definition 7.5 (time resources).
The model gives us , the set of -values that can be produced in units of time. Even though the category is a preorder in this case, and thus conversions have no useful content, the presheaf model lets us associate arbitrary sets to base types. For instance, assuming that we have the base type of natural numbers, we can let be the subset of natural numbers which can be generated in units of time or less. For instance, picturing a unary representation, we may have . For any and any we have . Indeed, the order is opposite to the usual order on natural numbers, and witnesses , and thus . That is to say, when getting more time, one can still produce (at least) the same values. In fact this inclusion is true for all types. In general, corresponds to values which are ready now, and corresponds to values which will be ready units of time in the future.
REMARK 6. The category W is a semi-lattice (Definition 5.8), and thus both products coincide:
In timing terms, the pair is ready when both components are ready; so with this setup the model corresponds to maximal parallelism. Additionally function application does not take any time all (24): the result of a function application is ready when both the function and the argument are ready. In order ascribe time to primitive functions, we can annotate their type with a modality, as explained below.
Modalities correspond to relative timings, or delays, which we can choose to be in . Their structure is borrowed from the so-called arctic semiring:
Definition 7.6 (timing modalities).
REMARK 7. The above structure forms a ring and is an extension of the monoidal structure of time as resource, so it is clear that forms a modality-resource module.
Definition 7.3 simplifies to:
by definition
by closure of A
Hence, qualification by adds an artificial waiting time of . Equivalently, it lets us consider the values that were ready -time in the past. Thus is interpreted as a function converting an -value that was ready -time in the past to a -value ready now. In more direct terms, this type refers to a function taking time to perform its work. The principles match well with this meaning of modalities. For instance, lift lets us add arbitrary waiting times, and the product principle becomes and corresponds to compounding delays.
7.2 Completeness
It may be still unclear if the resource model can account for arbitrary functors, such as (co)monadic effects. It can: the key is to use a modality-resource module which captures exactly how a type can be constructed, by letting resources be objects and modalities be functors. By fully reflecting the SMC , & structure, this instance of the resource model is complete wrt. the chosen SMC , &.
Complete model. Let us pick an arbitrary SMC & C. Then let the resource structure arise from the monoid from C ✓ and the associated scalars be the endofunctor modalities: . ✓ Then we have a modality-resource module. The operation is the action of those functors. The module properties are immediate consequences of the definitions. In particular, the distributivity properties are satisfied thanks to Lemma 4.4. In the arising presheaf model, a value contains C morphisms.
THEOREM 7.7 (COMPLETENESS). Assume arbitrary base types and arbitrary modalities . Let , and . Then any type can be interpreted to an object in , and:
Given coming from the complete model, we can construct a morphism
PROOF. We prove the following two lemmas by mutual induction on the structure of the type A:
Reification If an object X produces A in the sense of the complete model, then it also produces its interpretation, via a morphism. That is, given an element , we can construct a morphism . Its definition is:✓
Furthermore, reification is natural: .
Reflection The interpretation of a type as an object produces it in the sense of the resource semantics: for every type A there is an element . ✓ The
Jean-Philippe Bernardy and Andreas Abel
definition is:
8 Normal Syntax
We now have the groundwork laid out to derive a normalising syntax. Observe that Theorem 7.4 can be used to map to a category of presheaves over resources. The morphisms in the presheaf category effectively perform the computations in Set (the set of values). We also have completeness, which maps back to C via . Thus, the composition of these two results provides a normalisation by evaluation (NbE) procedure [11]. Much of the literature on NbE is concerned with the computation of normal forms per se, but here we will also use it to derive the syntax of normal forms. We could let C be the free , but it is preferable to target a language which excludes redexes by construction. This property is ensured by dividing the language into two separate syntactic categories, one for constructors and one for eliminators. Additionally, we'd rather not target a category (which would yield a point-free language), but rather a lambda calculus with usual named variables. We write for the typing judgement associated with constructors. Strikingly, the contexts for this language cannot be contexts. Instead, we must use the free modality-resource module generated by syntactic modalities (for scalars) and types (for resources). In practice, this means two things. First, the syntax for contexts is extended with explicit scaling:
Second, patterns are extended with the means to manipulate such scaling. In fact, scaling patterns is not sufficient, one must scale whole pattern bindings. The resulting syntax is shown in Fig. 3. These pattern bindings correspond to the laws of a modality-resource module.
The associated presheaf semantics arising from the resource structure of (↔) provides a notion of value, . Theorem 7.4 gives us that any term evaluates to an element of . We can proceed as in the proof of completeness. The following two lemmas are then proven by mutual induction on the type :
Reification Given a value , we can construct a normal form .
Reflection For any type A, there is a value
We discuss normal forms below, in conjunction with the reification lemma. But let us focus on reflection first. Its proof follows the same structure as the corresponding lemma in the completeness theorem. Whenever a morphism is used in the completeness proof, we add it to the generators of the pattern binding syntax as an explicit eliminator, one for each type (Fig. 3). These eliminators work on variables and bind their results to variables directly, rather than acting on arbitrary terms as in . Notably, the application rule applies a function (variable x) to a normal form (t). In sum, the ( ) sub-language corresponds to generalized eliminators.
Indeed, in context scaling distributes on contexts by definition, and consequently it would not be possible to reflect types.
Pattern binding composition (Category structure)
Context reordering (Symmetric monoidal structure)
Context scaling manipulation (functorial properties thereof)
Eliminators
Term binding
Normal forms (constructors)
Fig. 3. Syntax of . ✓ . We resort to a point-free syntax for scaling pattern bindings, because such scaling operations do not touch variable names or types; only modalities. The symbol means that one can convert in both directions. For instance, stands for and . The associators of the symmetric monoidal structure are silent.
It remains to spell out the reification lemma. In the Theorem 7.7, the corresponding lemma builds a morphism in the chosen category, which in this section would be . Applying the recipe literally would mean adding constructors to that category, mixing them with eliminators. But then it would not be obvious that terms are normalised. So instead we define a new syntactic category of normal forms, . To find out its inhabitants, we
Jean-Philippe Bernardy and Andreas Abel
simply follow the structure of Theorem 7.7 and assert the pieces of syntax which we need, one for each type.
What we have obtained is a polarised syntax for our semantics. That is, every intermediate result is bound to a variable.✓ A property of the constructor forms is that they can always be prefaced by a pattern binding. That is, the following rule is admissible:
. The idea is that the bindings can be pushed down the syntax tree until reaching one of the constructions with native binding (variable, or ) and inserted there. Note that this procedure never performs a computation: it consists in prepending a context transformation before constructors, not the other way around. This operation the restriction map for , as a presheaf.
The equational theory of the pattern-binding fragment is given by the laws of a modality-resource module (Fig. 4). Those correspond to commuting conversions in sequent calculi presentations. Equality for just a congruence for each constructor. However, congruence for and is unusual: they assert that bindings can equally be applied to the compound or to the constituents, as in the presheaf semantics.
9 Completing the calculus
Unlike , the language of normal forms presented above has a (well-behaved) equational theory. However, by definition, it contains only normal forms and thus cannot represent computation. This shortcoming is addressed in this section. The resulting language is called . We prove that retains all the desirable theoretical properties of a core calculus. One top of normal forms, we only add the binding of an arbitrary term: ✓
The equational theory is extended with administrative rules for term bindings, naturality laws of for the manipulation of context scaling, and computational rules for each type (Fig. 4). This completes the definition of . It admits the same models as : given a modality functor into endofunctor modalities, terms can be evaluated into any SMC C, in a straightforward manner. ✓ This interpretation, , is complete with respect to term equality: if then . ✓
Because both and are interpreted into the same categorical structure, is subject to the same normalisation by evaluation procedure as . To reiterate, one first evaluates in the presheaf category over eliminators, then reifies into normal forms: . ✓ Since lacks an equational theory, we could not prove, or even state, any useful property of its normalisation procedure. However, we can do so for :
THEOREM 9.1 (SOUNDNESS OF NORMALISATION FOR ). for any . ✓
PROOF. The proof follows the standard pattern. A logical relation (∼) is defined between terms and values. ✓ The result falls out of the combination of two lemmas: the fact that values are related to their reification (v ~ ↓v) ✓ and the fundamental lemma of logical relations.✓
As corollaries, we have:
• stability: and
| Equivalence | ||
|---|---|---|
| Laws of a modality-resource module (naturality of context scaling manipulation) | ||
| Administration of let bindings | ||
| Computational rules | ||
| Congruence for constructors | ||
Fig. 4. Equational theory for . We omit the usual SMC laws (equivalence, naturality) as well as congruence rules for pattern bindings: they are unsurprising.
- preservation of meaning: .
Finally, we can show that the semantics of and agree. To do this, we construct the syntactic category of terms, hereafter called Syn. Syn is a SMC where objects are types, and any morphism is a term .
THEOREM 9.2. For any C and any , we have .
As a corollary, the normal forms obtained directly from terms are the same as those that one would obtain by first translating them to . The following diagram depicts the possible interpretations, as well as reification ()

Jean-Philippe Bernardy and Andreas Abel
In the above, refers to the presheaf category over the category.
In summary has a well-defined semantics, but reasoning about programs cannot be done using its syntax. If syntactic reasoning is needed, it one can safely translate first into .
10 Related work
At its core, our framework is syntactically and semantically based on linear logic [18]. The generalisation of modalities to ring-like structures is due to Girard et al. [20], and further refined, inter alia, by Dal Lago and Hofmann [12] or Ghica and Smith [16].
The idea of interpreting modalities as functors can be traced at least to Ghilardi and Meloni [17], and more explicitly Bierman and de Paiva [8]. Brunel et al. [9] lays the concrete groundwork which we build upon. The principal generalisations that we offer are those listed in the introduction: we don’t require distributivity (monoidal functors), and we explicitly allow computational content in the modality structure, but we also unify the treatment of effects and coefficients, as well as quantitative modalities. (The requirement on distributivity and monoidal functor pervades literature which extends modality applications in several ways, i.a. the work of Gratzer et al. [21].) Another difference is that Brunel et al. propose a realisability semantics which resembles our resource semantics, but it features (double) orthogonalisation, and as such cannot be made an instance of the general categorical semantics. Additionally, we provide a completeness theorem and support (&) products.
Finally, Brunel et al. sustain the converse of the sum principle: . For arrays, such a principle would correspond to concatenation, and it is central in the fractional ownership system of Makwana and Krishnaswami [27], so it is clearly useful for some applications. The main reason for us leaving it out is that we could not make sense of it with regard to substitution. Indeed, it demands that two substitutions and can be merged, which appears impossible in general.
Abel and Bernardy [2] have proposed a unified framework for modalities in type-systems similar to ours, and have provided the relational semantics combining parametricity interpretations [36], classified sets [1, 23], and resource indexing [7, 9]. We have made this semantics an instance of the more general categorical framework, hoping to make it more approachable. Additionally, we support non-distributive modalities and our semantics is proven complete. Abel and Bernardy natively support coproducts, whereas we encode them using inversion of control. It leads them to propose that sum types can be analysed iff they are qualified with a modality . According to our semantic interpretation, the condition on is the existence of a morphism . In sum, our framework provides a semantic reason for the fact that sensitivity analysis treats coproducts differently from other systems. We propose that supporting sum requires shifting to a semantics based on sheaves (instead of presheaves). The treatment of Altenkirch et al. [6] should be adaptable to our setting, but we leave it as future work.
Modalities as 2-categories and arbitrary functional interpretations. In a recent line of work, Kavvos [24, 25] has proposed to interpret modalities as functors. Kavvos does not consider generic modality structures as we do, but concentrate on the case of dual modalities and an underlying cartesian category where (&) and (⊗) coincide. However Kavvos, similarly to Orchard et al. [33], offers another interesting direction of generalisation: for him modalities are not a set, but rather morphisms in a category. The objects of this category are called modes. It appears that can be generalised in this direction: the relation ( ) becomes the hom-set of a 2-category and the typing relation is indexed by a mode , as in . The semantic interpretation would target a family of monoidal categories , and modalities would be interpreted as functors between those. Working out the details, in particular the generalised resource-semantics and its implications, is left as future work.
To our knowledge, the present work is the only one to offer a fully mechanised formalisation.
Semantics. The resource semantics can be considered a reformulation of that of Abel and Bernardy [2] in a presheaf framework. O'Hearn and Pym [31] defined the same semantics much earlier, but for a language lacking modalities altogether. The presheaf semantics of tensor products have been studied by Day [13]. The presheaf semantics for functors can be traced to Day and Street [14]. They are primarily interested in monoidal functors, but what we use (the left Kan extension) carries over to our setting.
11 Discussion
Type-checking. We have focused primarily on semantics, but any concrete language based on it should feature a typechecker. As presented, the -INTRO and APP rules split the context non-deterministically, and it may not be clear how this split should be implemented in a typechecker. One solution is to let the typing rules to return a context of unused variables [5]. Additionally, for type checking to be possible, the set of modalities need a decidable equality in addition to the structure necessary for semantic purposes.
Type-Polymorphism. We have chosen to leave out polymorphism from our development, for the following reasons: 1. Polymorphism is mostly orthogonal from our concerns. The only interaction happens in the encoding of sums, but that is invisible except for the discussion (1) of case analysis for sensitivity. 2. A relational treatment of polymorphism does not fit the simple categorical framework. One would have to bring out at least the concept of display category [3]. Even though we have not presented this version in the paper, some results based on this approach are available in our formalisation. ✓
Even fewer structural rules. We have considered modalities which limit duplication and discard of variables, but one can also use them to, for instance, control movement (associativity and commutativity) of variables in the context [29]. Support for this even more general case could work in a similar way as our treatment of (optional) distributivity over products, but is left for future work.
Poset modalities. We have considered modalities which form a category, which is a computationally-relevant version of a poset. This lets us support arbitrary effects (see Remark 3). This means that in general modality conversions must be explicit in syntax. In contrast, if one assumes irrelevant conversions, one can on the contrary let the type-checker infer such conversions, as Orchard et al. [32] do. But, one can also compute whether there is a single conversion, and use it if it is unique or report an error otherwise.
12 Conclusion
We have shown that general functional programming can be expressed using the syntax typically reserved for modalities or grade, albeit with some tweaks. Certain syntactic constructs are reserved to (op)lax functors, and when multiple natural transformations exist between functors, conversions between modalities must be made explicit.
Jean-Philippe Bernardy and Andreas Abel
Our language unifies what is traditionally seen as modalities (quantitative applications) and as functors (data structures, effects, coefficients). The functional-programming community has proposed a variety of surface syntax for each domain—do-notations, idiom brackets, parallel list comprehensions, etc. Our proposal subsumes these alternatives, even when all these applications are mixed in a single program. It does so with only a handful of syntactic elements. Although there is some syntactic overhead (particularly for effects), it can be mitigated with syntactic sugar. In cases where modality conversions can be inferred, the syntax can even be lightweight.
Given that modalities are, in fact, functors, why not program directly with those functors? Indeed, functorial and (co)monadic programming is already possible today, but it requires juggling with a zoo of combinators. We argue that a direct syntax—much like lambda notation’s advantage over SKI combinators—offers a clearer, more ergonomic approach.
References
[1] M. Abadi, A. Banerjee, N. Heintze, and J.G. Riecke. 1999. A core calculus of dependency. In Proceedings of the 26th ACM SIGPLAN-SIGACT symposium on Principles of programming languages. ACM, 147–160.
[2] Andreas Abel and Jean-Philippe Bernardy. 2020. A unified view of modalities in type systems. Proceedings of the ACM on Programming Languages 4, ICFP (2020).
[3] Benedikt Ahrens and Peter LeFanu Lumsdaine. 2019. Displayed Categories. Logical Methods in Computer Science Volume 15, Issue 1 (March 2019). https://doi.org/10.23638/lmcs-15(1:20)2019
[4] Maximilian Algehed and Jean-Philippe Bernardy. 2019. Simple noninterference from parametricity. Proceedings of the ACM on Programming Languages 3, ICFP (2019), 89.
[5] Guillaume Allais. 2017. Typing with Leftovers - A mechanization of Intuitionistic Multiplicative-Additive Linear Logic. In 23rd International Conference on Types for Proofs and Programs, TYPES 2017, Budapest, Hungary, May 29 - June 1, 2017 (LIPics), Andreas Abel, Fredrik Nordvall Forsberg, and Ambrus Kaposi (Eds.), Vol. 104. Schloss Dagstuhl - Leibniz-Zentrum für Informatik, 1:1–1:22. https://doi.org/10.4230/LIPICS.TYPES.2017.1
[6] Thorsten Altenkirch, Peter Dybjer, Martin Hofmann, and Philip J. Scott. 2001. Normalization by Evaluation for Typed Lambda Calculus with Coproducts. In 16th Annual IEEE Symposium on Logic in Computer Science, Boston, Massachusetts, USA, June 16-19, 2001, Proceedings. IEEE Computer Society, 303–310. https://doi.org/10.1109/LICS.2001.932506
[7] Robert Atkey and James Wood. 2018. Context constrained computation. In Third Workshop on Type-Driven Development (TyDe'18). https://personal.cis.strath.ac.uk/james.wood.100/pub/context-constrained.pdf
[8] Gavin M. Bierman and Valeria CV de Paiva. 2000. On an intuitionistic modal logic. Studia Logica 65, 3 (2000), 383–416.
[9] Aloïs Brunel, Marco Gaboardi, Damiano Mazza, and Steve Zdancewic. 2014. A Core Quantitative Coeffect Calculus. In Programming Languages and Systems - 23rd European Symposium on Programming, ESOP 2014, Held as Part of the European Joint Conferences on Theory and Practice of Software, ETAPS 2014, Grenoble, France, April 5-13, 2014, Proceedings (Lecture Notes in Computer Science), Zhong Shao (Ed.), Vol. 8410. Springer, 351–370. https://doi.org/10.1007/978-3-642-54833-8_19
[10] Ranald Clouston. 2018. Fitch-style modal lambda calculi. In International Conference on Foundations of Software Science and Computation Structures. Springer, 258–275.
[11] Thierry Coquand. 1991. An algorithm for testing conversion in type theory. Logical frameworks 1 (1991), 255–279.
[12] Ugo Dal Lago and Martin Hofmann. 2009. Bounded linear logic, revisited. In Typed Lambda Calculi and Applications. Springer, 80–94.
[13] Brian Day. 1970. On closed categories of functors. In Reports of the Midwest Category Seminar IV. Springer-Verlag, 1–38.
[14] Brian Day and Ross Street. 1995. Kan extensions along prononoidal functors. Theory and applications of categories 1, 4 (1995), 72–77.
[15] Arthur Azevedo de Amorim, Marco Gaboardi, Justin Hsu, Shin-ya Katsumata, and Ikram Cherigui. 2017. A semantic account of metric preservation. In Proceedings of the 44th ACM SIGPLAN Symposium on
Principles of Programming Languages, POPL 2017, Paris, France, January 18-20, 2017. 545–556. http://dl.acm.org/citation.cfm?id=3009890
[16] Dan R. Ghica and Alex I. Smith. 2014. Bounded Linear Types in a Resource Semiring. In Programming Languages and Systems - 23rd European Symposium on Programming, ESOP 2014, Held as Part of the European Joint Conferences on Theory and Practice of Software, ETAPS 2014, Grenoble, France, April 5-13, 2014, Proceedings. 331–350. https://doi.org/10.1007/978-3-642-54833-8_18
[17] Silvio Ghilardi and GC Meloni. 2006. Modal and tense predicate logic: models in presheaves and categorical conceptualization. In Categorical Algebra and its Applications: Proceedings of a Conference, held in Louvain-La-Neuve, Belgium, July 26–August 1, 1987. Springer, 130–142.
[18] Jean-Yves Girard. 1987. Linear logic. Theoretical Computer Science 50, 1 (1987), 1–101.
[19] Jean-Yves Girard. 1991. A new constructive logic: classical logic. Mathematical Structures in Computer Science 1, 3 (1991), 255–296.
[20] Jean-Yves Girard, Andre Scedrov, and Philip J. Scott. 1992. Bounded linear logic: a modular approach to polynomial-time computability. Theoretical Computer Science 97, 1 (1992), 1–66. https://doi.org/10.1016/0304-3975(92)90386-T
[21] Daniel Gratzer, G. A. Kavvos, Andreas Nuyts, and Lars Birkedal. 2021. Multimodal Dependent Type Theory. Log. Methods Comput. Sci. 17, 3 (2021). https://doi.org/10.46298/LMCS-17(3:11)2021
[22] Ralf Hinze. [n.d.]. Monads from Comonads, Comonads from Monads. https://www.cs.ox.ac.uk/ralf.hinze/WG2.8/28/slides/Comonad.pdf
[23] Georgios Alexandros Kavvos. 2019. Modalities, cohesion, and information flow. Proceedings of the ACM on Programming Languages 3, POPL (2019), 20:1–20:29. https://doi.org/10.1145/3290333
[24] Georgios Alexandros Kavvos. 2024. Two-Dimensional Kripke Semantics I: Presheaves. In 9th International Conference on Formal Structures for Computation and Deduction, FSCD 2024, July 10-13, 2024, Tallinn, Estonia (LIPIcs), Jakob Rehof (Ed.), Vol. 299. Schloss Dagstuhl - Leibniz-Zentrum für Informatik, 14:1–14:23. https://doi.org/10.4230/LIPICS.FSCD.2024.14
[25] G. A. Kavvos. 2024. Two-dimensional Kripke Semantics II: Stability and Completeness. CoRR abs/2406.03578 (2024). https://doi.org/10.48550/ARXIV.2406.03578 arXiv:2406.03578
[26] Anders Kock. 1972. Strong functors and monoidal monads. Archiv der Mathematik 23, 1 (1972), 113–120.
[27] Dhruv C. Makwana and Neelakantan R. Krishnaswami. 2019. NumLin: Linear Types for Linear Algebra. In 33rd European Conference on Object-Oriented Programming, ECOOP 2019, July 15-19, 2019, London, United Kingdom (LIPIcs), Alastair F. Donaldson (Ed.), Vol. 134. Schloss Dagstuhl - Leibniz-Zentrum für Informatik, 14:1–14:25. https://doi.org/10.4230/LIPIcs.ECOOP.2019.14
[28] Conor McBride and Ross Paterson. 2007. Applicative programming with effects. Journal of Functional Programming 18, 01 (2007), 1–13. https://doi.org/10.1017/S0956796807006326
[29] Michael Moortgat. 1996. Multimodal Linguistic Inference. J. Log. Lang. Inf. 5, 3/4 (1996), 349–385. https://doi.org/10.1007/BF00159344
[30] Tom Murphy, Karl Crary, and Robert Harper. 2005. Distributed Control Flow with Classical Modal Logic. In Computer Science Logic, 19th International Workshop, CSL 2005, 14th Annual Conference of the EACSL, Oxford, UK, August 22-25, 2005, Proceedings (Lecture Notes in Computer Science), C.-H. Luke Ong (Ed.), Vol. 3634. Springer, 51–69. https://doi.org/10.1007/11538363_6
[31] Peter W O'Hearn and David J Pym. 1999. The logic of bunched implications. Bulletin of Symbolic Logic 5, 2 (1999), 215–244.
[32] Dominic Orchard, Vilem-Benjamin Liepelt, and Harley Eades III. 2019. Quantitative program reasoning with graded modal types. PACMPL 3, ICFP (2019), 110:1–110:30. https://doi.org/10.1145/3341714
[33] Dominic Orchard, Philip Wadler, and Harley Eades. 2020. Unifying graded and parameterised monads. Electronic Proceedings in Theoretical Computer Science 317 (May 2020), 18–38. https://doi.org/10.4204/eptcs.317.2
[34] Tomas Petricek, Dominic A. Orchard, and Alan Mycroft. 2014. Coeffects: a calculus of context-dependent computation. In Proceedings of the 19th ACM SIGPLAN international conference on Functional programming, Gothenburg, Sweden, September 1-3, 2014, Johan Jeuring and Manuel M. T. Chakravarty (Eds.). ACM, 123–135. https://doi.org/10.1145/2628136.2628160
[35] Jason Reed and Benjamin C. Pierce. 2010. Distance makes the types grow stronger: a calculus for differential privacy. In Proceeding of the 15th ACM SIGPLAN international conference on Functional programming, ICFP 2010, Baltimore, Maryland, USA, September 27-29, 2010, Paul Hudak and Stephanie Weirich (Eds.).
Jean-Philippe Bernardy and Andreas Abel
ACM Press, 157–168. https://doi.org/10.1145/1863543.1863568
[36] John C. Reynolds. 1983. Types, abstraction and parametric polymorphism. Information processing 83, 1 (1983), 513–523.
[37] Dana S Scott. 1980. Relating theories of the lambda calculus. To HB Curry: Essays on combinatory logic, lambda calculus and formalism (1980), 403–450.
[38] David Walker. 2005. Substructural Type Systems. In Advanced Topics in Types and Programming Languages, Benjamin C. Pierce (Ed.). MIT Press, Chapter 1.
A Typing derivations
A.1 Duals
Admissibility of -INTRO.
Admissibility of -ELIM.
\begin{array}{c}\frac{\varepsilon:\bar{p}p\preceq1\quad\overline{A\vdash A}}{\bar{p}p A\vdash A}\\\boxed{\bar{p}}-INTRO\frac{\Gamma\vdash\boxed{p}A}{\bar{p}\Gamma\vdash\boxed{\bar{p}}\boxed{p}A}\left(|\Gamma|=1\right)\vee\delta(\bar{p})\quad\frac{\overline{\bar{p}}\boxed{p}A\vdash A}{\boxed{\bar{p}}\boxed{p}A\vdash A}\quad VAR\frac{\overline{A\vdash A}}{\end{array}Rule -INTRO from -INTRO.
A.2 Effects
bind.
Jean-Philippe Bernardy and Andreas Abel
example program (increment with state effect).
A.3 Co-effects
example program (increment with coeffect).
duplication of coeffect sources.