Manuscript Offprint
arXiv:2610.27519Record Types Everywhere
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
A Record Calculus for Arguments and First-Class Environments
MATTHEW TOOHEY, University of Toronto, Canada
ARA JAMALZADEH, University of Toronto, Canada
NINGNING XIE, University of Toronto, Canada
This paper introduces a novel calculus that models first-class environments and function application paradigms using standard record types. By proposing new extensions to general record types, we achieve a design that is remarkably simple and principled. We formalise this design in a core calculus and prove several desirable properties, including type soundness, normalization, and a simulation of the simply typed lambda calculus. Additionally, we extend the design with mutable references. The calculus, its semantics, along with the extension, and all stated properties are fully mechanized in the Lean 4 proof assistant, alongside an interpreter formally verified to be equivalent to the operational semantics.
1 Introduction
The lambda calculus [Church 1941] provides a foundational model for computation and serves as the theoretical basis for modern functional programming languages. A lambda abstraction . e denotes a function binding a variable within the body expression , with its core evaluation step defined by the -reduction rule via substitution: .
However, managing variable bindings remains a classic challenge in language implementation, reasoning, and mechanization. In particular, ensuring variable freshness can be quite tricky. While paper formalisms and pen-and-paper proofs often assume -equivalence, concrete implementations typically require more complex machinery such as de Bruijn indices [de Bruijn 1972] to define capture-avoiding substitution. De Bruijn indices, however, are famously difficult to formalise and implement correctly. Moreover, substitution and de Bruijn indices are often inefficient because reduction requires a traversal of the expression body. Finally, -reduction fails to capture many common argument-passing paradigms such as named arguments, which allow arguments to be supplied by explicit parameter names.
In this paper, we show how standard record types can be leveraged to model first-class environments [Gelernter et al. 1987; Sato et al. 2001; Tan and Oliveira 2024] and function arguments, establishing an environment-based model that sidesteps traditional binding and inefficiency issues while capturing diverse function application paradigms. Our design is remarkably simple and principled; it uncovers subtle interactions that emerge when combining features and provides a general framework for function application paradigms by exploiting inherent record properties.
We offer the following contributions:
• A novel design: We propose a design that models first-class environments and function arguments using standard record types ( ). Specifically, our design:
– Is simple and principled, yet naturally expresses diverse features, including first-class environments ( ), along with named ( ), positional ( ), and optional ( ) arguments, while supporting a form of partial application ( , ).
– Generalizes traditional function application paradigms to general records ( ); and
– Unifies disparate approaches to handling duplicate labels in record calculi [Leijen 2005; Rémy 1994] ( ).
Authors' Contact Information: Matthew Toohey, University of Toronto, Toronto, Canada, mtoohey@cs.toronto.edu; Ara Jamalzadeh, University of Toronto, Toronto, Canada, a.jamalzadeh@mail.utoronto.ca; Ningning Xie, University of Toronto, Toronto, Canada, ningningxie@cs.toronto.edu.
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
• Formalisation: We formalise this design as a core record calculus, ( ). We establish key structural properties of its record operators (Lemma 3.1-3.6), determinacy (Theorem 3.7), type soundness (Theorems 3.8 and 3.9), and normalization (Theorem 3.11). We also prove that it simulates the simply typed lambda calculus (Theorems 3.14 and 3.15).
• Imperative extension: We extend the calculus with mutable references, under which the precise behaviour of function application becomes important ( ). To safely handle type generalization in the presence of side-effects, we adopt the approach of Dolan [2024] and adapt it to closures and applications.
• Mechanization: The calculus, including its operational semantics and all stated lemmas and theorems, is fully mechanized in the Lean 4 proof assistant ( ). The complete proof artifact is provided in the supplementary materials.
• Implementation: We implement an interpreter for and formally verify its equivalence with the operational semantics (Theorem 5.1).
Lastly, we explore the broader design space in §6.
2.1 The Lambda Calculus with the Substitution Model
Functions, or lambdas, are the core abstraction in the lambda calculus [Church 1941]. Its two fundamental rules, governing typing and evaluation respectively, are presented below:
Rule LAM type-checks a function by extending the typing context with the argument's type to type-check the body , resulting in the function type . The evaluation rule BETA substitutes the variable with the argument within the body .
However, while these two rules are standard in presenting the lambda calculus, they are not without issues. We discuss below some of the challenges of reasoning about and implementing them.
Reasoning about bindings. Reasoning about variable bindings is notoriously difficult, as substitution complicates the metatheory. The substitution function must itself be defined with care: when substituting within a lambda . , it must respect shadowing when and coincide and, when reducing open terms, avoid capturing the free variables of . Type preservation then rests on a substitution lemma.
To manage bindings, it is common to assume the alpha-convention, where a bound variable can be renamed at any point to ensure its freshness. While this convention is standard in the literature, it does not directly yield a straightforward algorithm for implementation or mechanization.
Another well-known alternative is the use of de Bruijn indices [de Bruijn 1972], where variables are represented as natural numbers pointing to their corresponding binding sites. However, it is widely acknowledged that implementing and reasoning about shifting, the key operator in de Bruijn indices used to adjust binding numbers during substitution, can be error-prone and non-trivial.
Inefficiency of the substitution model. Another issue is that the substitution model is highly inefficient. Every substitution requires a full traversal of the expression, a process that becomes exceptionally expensive for functions with large bodies. Worse, nested applications trigger this substitution process multiple times, leading to a compounding cost.
Due to this inherent inefficiency, practical languages do not implement beta-reduction using the substitution model. Instead, it is much more common to utilize an environment-based model. Rather than eagerly rewriting the function body every time a variable is bound, the system maintains an environment that maps variable names to their actual values. Consequently, when a function is applied to an argument, the language simply adds that variable-value pairing to the current environment and proceeds to evaluate the function body. By avoiding substitution, an environment-based model also simplifies the metatheory [Tan and Oliveira 2024, §2.2 and §4.1].
In the literature, a body of work has focused on modelling environments, ranging from calculi with explicit substitutions [Abadi et al. 1989; Biernacka and Danvy 2007; Curien 1991] to the study of first-class environments [Gelernter et al. 1987; Sato et al. 2001; Tan and Oliveira 2024].
Missing function application paradigms. Furthermore, the vanilla lambda calculus does not natively support various function application paradigms common in practical programming languages. For example, many languages support named arguments, which significantly enhance programming convenience by allowing arguments to be provided with explicit names. To illustrate, consider a function written in Python syntax:
def transfer_funds(amount, from_account, to_account): ...
When a programmer wants to call this function using standard positional arguments, they must remember the exact order of the parameters:
transfer_funds(1000, "Alice", "Bob")
Without looking up the function’s definition, this code is difficult to read and highly error-prone. If a developer accidentally swaps "Alice" and "Bob", the code will still execute, but the funds will be transferred from and to the wrong person.
Languages that support named arguments, such as Python, allow programmers to specify the name of the parameter directly alongside the value at the call site:
transfer_funds(amount=1000, from_account="Alice", to_account="Bob")
This way, it becomes immediately clear from the call site which account is transferring to which.
Named arguments represent one example of function application paradigms; other important examples include, e.g. optional arguments, which we will discuss further in subsequent sections.
2.2 First-Class Environments as Records
In this paper, we develop an environment-based model for the lambda calculus by representing environments as records. This perspective is motivated by the close similarity between a typing context , which maps variables to their types, and a record type , which maps labels to types. Consequently, we can update the typing rule LAM to rule T-LAM below:
record type ::=
Records are typically expected to be commutative, a property usually captured by a subtyping rule that permutes fields. Under this view, for example, { name:String, age:Int } is equivalent to { age:Int, name:String }. This equivalence naturally reflects the intuition that the typing context is unordered. Therefore, we can formulate a variable typing rule T-VAR as shown on the right, which, instead of requiring , simply requires i to be the T-VAR final entry in the context.
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
Closures. Similarly, during evaluation, an environment record value o tracks the values bound to variables. As a result, evaluating lambdas produces closures that capture the variable bindings along with the function:
record value o ::=
E-LAM
When the closure is applied to an argument, the function body e is then evaluated under the environment o extended with i bound to that argument.
First-class environments. With first-class environments [Gelernter et al. 1987; Sato et al. 2001; Tan and Oliveira 2024], we can treat environments as first-class objects that can be directly manipulated. For example, we can introduce an operator @ that reifies the environment into a record, with the typing rule and the evaluation rule . We can then apply record operators, such as projection, to the environment. In particular, a variable i can be considered syntactic sugar for @.i, which reifies the environment and then projects out the i field. As another example, a box operator evaluates within the environment , allowing us to directly manipulate the environment in which an expression is evaluated.
As demonstrated by Tan and Oliveira [2024], first-class environments are useful for modelling first-class modules [Cardelli 1997], sandboxed modules, and object capabilities [Miller 2006; Miller et al. 2000]. Our representation of environments as records naturally supports these paradigms, since record objects are themselves first-class.
2.3 Named Arguments as Records
Having observed how function applications with named arguments operate in our transfer_funds example, another natural perspective we take is to represent function arguments as records.
That is, functions are now typed as , allowing them to introduce multiple entries into the context. We introduce record patterns with the following typing rule T-LAM2:
record pattern
Here, the record pattern defines named function arguments. Rule T-LAM2 assigns the type to the record pattern , and updates the typing context to , which simply appends to .
As an example, we can define transfer_funds as follows:
. ...
Function applications can now provide records as named arguments at the call site. For example, the previous example can be written as:
transfer_funds { amount=1000, from_account="Alice", to_account="Bob" }
Thanks to record commutativity, this is equivalent to the following expression, as is desired:
transfer_funds { to_account="Bob", from_account="Alice", amount=1000 }
Shadowing in first-class environments. One may wonder what happens when and in rule T-LAM2 share same labels. We support duplicate labels (or scoped labels [Leijen 2005]), which, as we represent environments as records, arise naturally in an environment when shadowing occurs.
Duplicate labels are non-commutative with respect to each other, while remaining commutative with different labels. Specifically, projecting a duplicate label from a record returns the rightmost corresponding field (unlike [Leijen 2005], which always returns the leftmost one). For example, .i returns 1. To access the second rightmost one, we can simply write
({ i=2, i=1 }\i).i, which removes () the rightmost i field from the record, and then accesses the i field, which effectively retrieves the shadowed i value 2.
The interpretation that projecting a duplicate label retrieves the rightmost corresponding field directly coincides with the fact that new variables are always appended to the right of an environment (as in rule T-LAM2), thus shadowing prior ones. Therefore, our previous syntactic sugar @.i for variable lookup still holds, as it accesses the latest i field in the environment. With first-class environments, we can also easily access shadowed fields, e.g. by (@\i).i.
2.4 Argument Labels and Parameter Names
We can further separate external argument labels, used at the call site, from internal parameter names, used within the function definition. This distinction allows a function call to read like a sentence, while keeping the function definition itself clear and logical.
The following Swift program, adapted from its official documentation, illustrates this distinction between argument labels and parameter names (the -> String annotation specifies the return type):
func greet(person: String, from hometown: String) -> String { "Hello_\(person)from\(hometown)." }
Here, person and hometown bind to the parameters within the function body, while from serves as the argument label used at the call site. We can then call the function as:
greet(person: "Alice", from: "Mars") // "Hello Alice from Mars"
To support the distinction between argument labels and parameter names, we can generalize both record patterns and the typing rule T-LAM2 to rule T-LAM3:
record pattern
Here, the record pattern captures the distinction () between argument labels and parameter names, which are separated () in T-LAM3 and assigned to record types and . For example, can be separated into Int and Int. The former, , represents the external argument labels and is used as the argument type in the conclusion, while the latter, , represents the internal parameter names and extends the typing context for typing . The corresponding rule in §3.2 additionally performs generalization over the function type; we omit this here for simplicity.
We can now express the example as follows, assuming string interpolation:
$\lambda{ person, from \diamond hometown }. "Hello_\(person)_from_\(hometown)."
For clarity, we often omit the argument label (e.g. person) when it is identical to the parameter name.
2.5 Positional Arguments
The design so far requires every argument to be named. However, positional arguments remain valuable when parameter roles are intuitive enough that explicit labels would only add visual noise. For instance, a function sub(x, y) is naturally expected to compute rather than .
Languages that support named arguments often provide mechanisms for positional arguments as well. In Swift, for example, function arguments are named at the call site by default. When an argument label is unnecessary, Swift developers can use an underscore (___) as the argument label. For example, one can define sub in Swift as the following:
func sub(_ a: Int, _ b: Int) -> Int { a - b }
Here the underscores indicate that the function can be called with positional arguments. This allows the argument labels to be omitted at the call site, e.g. sub(8, 3).
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
It turns out we can naturally support positional arguments using duplicate labels ( ). Specifically, by treating the underscore ( $_) as a normal field label, we can define sub as
sub = λ{ _ ◇ a, _ ◇ b }. a - b
The positional application sub {8, 3} can then be desugared simply into sub {_ = 8, _ = 3}, where the argument { _ = 8, _ = 3} is a record with duplicate labels ( $_). Since duplicate labels do not commute with respect to each other, this effectively models positional arguments.
Mixing named and positional arguments. By interpreting positional arguments as normal records with duplicate labels, our design interprets positional arguments as simply a special case of named arguments. As noted, non-duplicate labels are commutative, while duplicate labels (including the dedicated label for positional arguments) are non-commutative with respect to each other (thus preserving the significance of their order), yet remain commutative with other labels.
As an example, if div is defined with a named dividend and a positional divisor:
div = λ{ dividend , _ ◇ divisor }. dividend / divisor
then both (div { dividend=4, 2 }) and (div {2, dividend=4 }) are valid and produce the same result, while (div {4, 2 }) is invalid, as named arguments can never be passed positionally.
Our design preserves simplicity by, like Swift, requiring arguments to be declared as named or positional (simply using a dedicated label) in the function definition, making the system easy to reason about. But unlike Swift, which requires the order of arguments at the call site to strictly match the order defined in the function declaration, our system ensures commutativity between distinct labels, allowing for expressive order mixing at the call site. This is particularly useful when combined with partial application, which we discuss below.
2.6 Partial Application
So far, we have assumed that all arguments are passed together in a single record. We now generalize this behaviour to support partial application, where only a subset of the arguments are provided at the call site. Partial application is particularly flexible when combined with named arguments and commutativity. For example, consider a function drop that takes a count and a list, and drops count elements from the list. We can fix the list argument and define a specialized dropN function simply by writing drop {list = ['a', 'b', 'c', 'd']}.
To achieve partial application, we introduce the following typing rule for function application:
Here, the function expects the arguments specified by , while the argument record provides . The judgement computes the remaining arguments, . In this case, it simply removes from , though the application process will become more sophisticated later. Consequently, the application yields a function that accepts the remaining arguments, typed as .
This rule can be refined in several ways. First, if is empty, the application does not change the function type at all. To eliminate such “dummy” applications, we can introduce the side condition . Second, when is empty, the resulting type is A. In this scenario, the application is actually saturated, allowing us to simplify the type to A; we will revisit this design choice in §2.7.
We now extend the evaluation rules to support partial application. Specifically, we extend closures to keep track of two record values: one for the environment, and the other for the arguments accumulated so far. This behaviour is captured by the following rules:
When a function abstraction evaluates to a closure, it initializes an empty record for the arguments (rule E-LAM2). Subsequent function applications then simply accumulate the provided arguments into this record (rule E-APP). This dual-record setup will serve us well in the next section. Once an application is fully saturated, a beta reduction can occur using all collected arguments (see also §2.7).
2.7 Optional Arguments
In many programming languages, the developer can specify a default value for parameters. For example, we may want to define an exponential function that squares its input by default:
power = λ{ base, exponent := 2 }. base ** exponent
Calling (power { base=3 }) returns 9, while calling (power { base=3, exponent=3 }) returns 27. We refer to arguments with default values as optional arguments, as they can be omitted at the call site, while other parameters are considered required arguments.
Integrating optional arguments into the record pattern is straightforward; we extend c to include an additional case where a default value v can be provided.
record pattern
We now discuss the typing and evaluation rules for optional arguments.
Typing optional arguments. Since functions with optional arguments such as power can be called with only the required arguments or with optional arguments overwriting the default values, their type signatures must reflect both arities, so that both (power { base=3, exponent=3 }) and (power { base=3 }) type-check and saturate the application.
To this end, we introduce optional types in record types:
record type
strength
A record field is now associated with a strength , which is either strong () or optional (?). When used in function argument types, () indicates a required argument and (?) indicates an optional argument. Then, to type-check a lambda definition with optional arguments, the separation operation () in the typing rule T-LAM3 can be extended to handle the additional case for and produce optional types in . For example, the power function can be typed as
{ base ▷ Int, exponent ? Int } → Int
The type indicates that base is a required argument while exponent is an optional argument.
To type-check function applications such as (power {base=3, exponent=3}) and (power {base=3}), we introduce subtyping rules between records. Importantly, the subtyping relation includes the following two rules (omitting other rules such as reflexivity):
In the first subtyping rule S-EMPTY, the premise ensures that all entries in have the optional strength, and the conclusion specifies that the empty record is a subtype of such a record. In the second rule S-EXT, the premises are standard, and the conclusion specifies that for the same field , the left type has strength ( ), while the right type has strength ( ) or (?).
With these subtyping rules, we can derive two subtyping relations on the type of power. First, { base ▷ Int, exponent ? Int } → Int ≤ { base ▷ Int, exponent ▷ Int } → Int. This relation holds because { base ▷ Int, exponent ▷ Int } ≤ { base ▷ Int, exponent ? Int } by rule S-EXT. Thus power can take two arguments, allowing (power { base=3, exponent=3 }) to type-check.
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
Second, we can derive: { base ▷ Int, exponent ? Int } → Int ≤ { base ▷ Int } → Int. This relation holds because { base ▷ Int } ≤ { base ▷ Int, exponent ? Int } by S-EXT and S-EMPTY. Thus, power can also take a single argument, allowing (power { base=3 }) to type-check.
Evaluation with optional arguments. We now discuss the evaluation rule for function application with optional arguments. A subtle aspect is that these default values can be overwritten at the call site. Therefore, we must distinguish between arguments that can be updated and those that cannot. To achieve this, we update record values as follows:
record value E-APP2
Here, means that the value for the label has been set, while means that has a default value , which can be overwritten when the caller provides an explicit value.
Consequently, the previous evaluation rule E-LAM2 can be straightforwardly updated to retrieve all default parameters from the record pattern c and use them to form the initial argument list with . The updated evaluation rule E-APP2 above now uses a record concatenation operation, , instead of simply as in rule E-APP. Intuitively, this operation allows arguments in to overwrite the default ones in , so that results in .
Partial application with optional arguments. Now that we have the ability to overwrite optional arguments, a natural question arises: is the following expression well-typed?
power { base = 3 } { exponent = 3 }
In other words, is power { base=3 } a partially applied function that still waits for a potential value to overwrite the optional argument, or is it a saturated application (using the default value) that immediately returns the evaluation result 9 and therefore cannot accept more arguments?
Swift does not natively support partial application. On the other hand, OCaml, for example, requires a positional argument to appear after any optional arguments, so that it can determine when those optional arguments should be “erased” and replaced with their default values. If an optional argument is placed last, OCaml issues a warning as it cannot determine when the caller has finished providing arguments. In this case, OCaml would issue this warning for the definition of power.
Our design prioritizes simplicity by requiring an explicit construct, denoted as force, to deterministically trigger the evaluation of an expression once it has received all its arguments, as given by rule T-FORCE. The rule states that when an expression e has received all its arguments and has type {} → A, force e explicitly triggers the computation to yield a result of type A. The use of an explicit force is somewhat reminiscent of call-by-push-value [Levy 2001, 2006], which distinguishes a computation from its thunk, where the thunk is a value that can be forced at any time. In our setting, a partially applied function can be viewed as always producing a value (since it merely accumulates arguments via the evaluation rule E-APP2), while its actual computation is only triggered by an explicit force.
Now, (power { base=3 }) can be considered either a partially applied function, meaning that (power { base=3 } { exponent=3 }) is well-typed, or a saturated application. This works because, in either case, the actual computation has not yet occurred, and power { base=3 } simply evaluates to a closure . base** exponent). To trigger evaluation, an explicit force is required: (force (power { base=3 }) triggers the computation and returns 9 by using the default value for the optional argument, whereas (force (power { base=3 } { exponent=3 })) first sets exponent to 3 and then triggers the evaluation to return 27.
2.8 Optional Values
So far, we have developed a system that integrates named, positional, and optional arguments, introducing both optional types and the necessary subtyping rules to handle them properly.
However, one aspect of this design remains somewhat unsatisfying: although we introduced the optional type (i?A), it is currently only utilized on the left-hand side of a function type, such as { i ? Int } → Int, and no standalone value of type { i ? Int } actually exists. Yet, how might such a value be useful? In the presence of duplicate labels, it turns out there is a subtle interaction between the subtyping rules and duplicate labels, which can be resolved by such values. Specifically, suppose we have a function (f : { i ? Int, i ? Int } → Int) that takes two optional arguments sharing the same label (i ? Int). This situation can easily arise when i is the positional label (_.). We assume the arguments have default values of 3 and 5, respectively. By subtyping, we have:
{ i ? Int, i ? Int } → Int ≤ { i ▷ Int } → Int
This holds because . The derivation on the right first applies rule S-EXT to match with the first , and then applies rule S-EMPTY to relate the empty record with the second .
Now, because (f : {i ▷ Int} → Int) holds via subtyping, we can type-check the application (f {i = 1}) which provides the value 1 for an optional argument. According to the subtyping derivation, (f {i=1}) always overwrites the first optional i rather than the second. However, if we wanted to overwrite the second optional i while leaving the first to take its default value, the current rules unfortunately offer no way to achieve this. The choice matters since it causes different behaviours, meaning we would expect the closure of f to store (i=1, i:5) in the first case, and (i:3, i=1) in the second.
To resolve this issue, we extend record values to introduce optional values, written as i ?:
Notably, an optional value does not carry a concrete value for , and it is assigned the record type , which now possesses a valid inhabitant. Moreover, an optional value is a first-class citizen that can be passed to or returned from a function just like any other value.
An optional value like is not particularly useful on its own, but it becomes highly helpful in the presence of duplicate labels. Because it occupies a specific i position within a record, it can be used to explicitly specify which i label is being targeted during function application. For instance, using the function f from the previous example, we can now write the application:
f { i?, i = 1 }
In this case, the application leaves the first label with its default value and explicitly sets the second to 1. In the evaluation rule E-APP2, the record concatenation operation handles an optional value by leaving the values in unchanged. For example, yields . Therefore, the closure of has . This use of optional values is analogous to the use of undefined in JavaScript and TypeScript, where a default parameter is used if an argument is explicitly passed as undefined.
2.9 Overwriting Arguments
In the record typing literature, approaches to handling duplicate labels generally fall into two camps. The first employs scoped labels [Leijen 2005], where both fields coexist in the record, but one shadows the other. The second employs overwriting [Rémy 1994], where extending a record
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
with an existing label overwrites the previous field. In our current formalism, duplicate labels correspond to the scoped approach. On the other hand, the behaviour of overwriting an optional argument closely resembles the latter camp.
Taking this observation further, it turns out that we can unify both approaches within our formalism by allowing record fields to specify whether they are overwritable. This design offers the benefit that it subsumes optional arguments as simply a special case of the unified design. Moreover, to our knowledge, this is the first system to combine scoped labels and overwriting labels, where all labels permit duplicates within a record, with overwriting behaviour managed via fine-grained, field-level specifications.
Specifically, we extend record types one final time to introduce the weak strength:
record type
strength
Here, and are as before, and represents a new strength which we refer to as weak, that denotes an overwritable field.
Conveniently, we have already introduced weak values in §2.7, which we used there to represent default values that can be overwritten at runtime. Therefore, the definition of record values from §2.8 (which previously incorporated optional values) serves as our final formulation.
Altogether, our system in its final form features three record strengths, along with their corresponding forms of record values. First, of type denotes a normal field. Second, of denotes an optional value. The type also indicates an optional argument on the left-hand side of a function; the intuition is that an optional argument can accept an optional value as it already carries a default. Finally, of type represents an overwritable field. §3 formally defines the static and dynamic semantics of records. In particular, core operations, including application and concatenation, are systematically defined based on record strengths.
Introducing the weak strength offers several benefits. First, it shifts the decision of whether to overwrite or bind a parameter from the parameters to the arguments. Under this mechanism, functions only require parameters of strength (:) . Thus, the separation operator in typing rule T-LAM3 yields records and of strength (:) .
We can also simplify record patterns by removing patterns with default values, effectively returning to the definition in §2.4:
record pattern
(from §2.4)
As an example, we can express the power function with a default exponent value of 2 simply as
power' = (λ{ base, exponent }. base ** exponent) { exponent : 2 }
Here, the lambda has type { base : Int, exponent : Int } → Int. It is applied to a record containing a weak value. As such, exponent gets the value 2 while remaining open to being overwritten, effectively yielding an optional argument; namely, power' : { base : Int, exponent ? Int } → Int.
We can then apply, e.g. (power' {exponent : 3}) to overwrite the default value. Notably, since the argument is itself an overwritable field, the resulting expression can be further applied to overwrite the exponent value again. On the other hand, applying (power' {exponent = 2}) will fix the exponent parameter. That is, the argument decides whether it provides a (new) default value for the parameter, or fully fixes it.
term
record value
Fig. 1. Syntax
2.10 Summary
We have discussed first-class environments represented via records, and demonstrated how records can also serve as function arguments, covering named, positional, and optional arguments, supported uniformly through three strengths over record types and values. Our design is certainly not the only viable one in the design space of function application paradigms. Indeed, different languages make different design choices, as we will discuss in §6.1. However, while many languages feature forms of named and optional arguments, their designs often exist only as implementation details rather than core formalisms.
The motivation for our formulation is threefold: first, to capture the core essence of these diverse paradigms and demonstrate how they can be expressed in a principled manner using familiar record types; second, to uncover the subtle interactions that arise when different features are combined; and third, to provide a framework that yields several advantages in terms of record commutativity, shadowing, and overwriting. The design also yields an intriguing record calculus by itself, naturally generalizing function application paradigms to general records such as optional and weak fields, which are useful for expressing various programs. Given that record types are widely utilized across various domains, we anticipate that our formulation can be inspiring in these areas as well; we expand on this discussion in §6.2.
3 A Record Calculus
This section presents the calculus, which formalises the features described in the prior section.
3.1 Syntax
Fig. 1 presents the syntax. Terms consist of natural numbers , lambdas . whose bindings are described by record patterns, closures containing record value components for the captured environment and accumulated arguments, applications , force expressions force , boxes , environment reification @, records , concatenation , projections , multi-projections , difference , and let expressions let in which support pattern-matching. Notably, variables are not included, as they are simply syntactic sugar for @.i.
Record patterns are either empty , or an extension , where the label specifies the argument label, and corresponds to parameter names. These record patterns are more general than those in §2; here, is either simply a parameter name , or a nested record pattern .
Records include the empty record , a regular extension , or an optional extension . The strength in regular extensions is called a required strength, either = or :, which ensures that an expression for the corresponding field must be present.
Values consist of natural numbers, as well as closures and records whose record entries are themselves values. Notably, they do not include lambdas, as we will discuss in §3.4.
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
(Typing)
T-CLOSURE
T-BOX
(Record Typing)
Fig. 2. Typing
(Subtyping)
(Record Subtyping)
(Strength Subtyping)
Fig. 3. Subtyping
Types A include type variables , natural numbers , function types , record types , and polymorphic types . A. Record types are either empty or an extension that maps a label to a type and a type-level strength. Type-level strengths consist of strong , weak :, and optional ?. Monotypes and record monotypes exclude polymorphism.
As a notational convenience, we also allow the = strength at the type level, treating it identically to ▷. This enables typing judgements such as . This means required strengths ★ can also appear at the type level when the optional strength ? must be excluded, e.g. for projections.
3.2 Typing
Fig. 2 presents the typing rules of our calculus. The typing judgement states that under , expression has type . Typing relies on the subtyping relation in Fig. 3 as well as auxiliary judgements in Fig. 4-6, which we elaborate on after explaining the typing rules. During typing, we preserve the invariant that always has strength (:) written . This invariant is maintained since when the environment is extended with a new entry, a term of the corresponding type always exists at runtime. Moreover, as noted in §2.9, functions only require parameters of strength (:)
Rule T-SUB is the standard subsumption rule. Rule T-LAM uses record pattern separation ( ) to extract argument labels and parameter names from the record pattern . The type is then generalized over the type variables . Notably, we perform generalization at function abstractions (as well as closures) rather than let-expressions, a design choice we justify in §4. Rule T-CLOSURE type-checks the captured environment and accumulated arguments under the empty context. ensures that all entries in have weak strength, and the relation computes the function's remaining arguments. The rule also performs generalization. Aside from its handling of quantifiers, which we also defer to §4, rule T-APP is straightforward. Rule T-FORCE eliminates a function type that expects an empty argument.
Rules T-BOX and T-ENV handle first-class environments, allowing records to be converted into environments and vice versa. Rule T-BOX also ensures that the entries of have weak strength.
To type-check a record, rule T-RECORD delegates to the record typing judgement , at the bottom of Fig. 2, which simply examines entries inductively. Rule T-CONCAT types record concatenation, where calculates the concatenated type. Rules T-PROJ, T-MPROJ, and T-DIFF follow a similar structure. Notably, all of them use required strengths, ensuring we can only project or subtract fields that actually exist.
Finally, T-LET first types , and then uses pattern separation to resolve the pattern t.
Subtyping (Fig. 3). The subtyping rules for types are largely standard, with rule S-QUANTL handling type instantiation. Record subtyping introduces more interesting design choices. Rule S-EMPTY allows a record type to be extended with entries at the end (as in §2.7). The hypothesis ensures that all such entries must have optional strength. When applied to function arguments, this behaviour allows us to forget optional arguments, such that their defaults are used. This is a limited, inverted form of width subtyping: we omit the usual rule, which would allow arbitrary entries to be dropped (see §6.2). Rule S-EMPTY has two important interactions with typing rules. First, it enables T-FORCE to expect a strictly empty argument list, instead of one containing an arbitrary amount of optional arguments. Second, it justifies why rules T-MPROJ and T-DIFF are restricted to fields with required strengths ; otherwise, rule S-EMPTY could be applied to introduce ambiguity, where a label could refer to either an existing field or an optional one introduced by subtyping.
In rule S-EXT, the strengths and of entry on the two sides are related by strength subtyping. The rule subsumes record permutation, allowing to commute with all entries in , as long as duplicate labels are not swapped. This is enforced by the premise . The typing rules T-PROJ, T-MPROJ, and T-DIFF utilize this permutation behaviour (through subsumption) to ensure the entries they manipulate are positioned at the tail of the record types within their premises.
Lastly, strength subtyping allows the weak strength : to be converted to optional ? (rule S-LT). When considered from the perspective of function arguments, this allows us to discard the default value of an optional argument, thereby converting it into a required one. Strength subtyping does not relate to anything other than itself, since doing so would prevent strong arguments from always having the intended effect of eliminating the corresponding function argument.
Pattern separation (Fig. 4). The judgement separates argument labels from parameter names in the record pattern . Rule P-EXT is more interesting: it recurses on the record pattern , and also uses the other judgement , which states that a parameter pattern produces an argument type and its corresponding parameter names . The result then extends with argument label , and extends with . Note that the weak strength : is used for the new argument entry, since all arguments start out as required. For the parameter pattern , rule
Notably, S-EXT traverses the first record from left to right. This keeps the rule simple; a right-to-left formulation is possible but, since S-EMPTY appends optional entries at the end, needs a slightly more involved condition on the occurrences of i.
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
(Record Pattern Separation)
P-EMPTY
P-EXT
P-LABEL
(Pattern Separation)
P-RECORD
Fig. 4. Pattern separation
(Record Type App)
A-EMPTY
A-WEAKSTRONG
A-OPTIONALSTRONG
A-EXT
(Strength App)
A-LATER
A-SET
A-LEAVE
?●?→?
A-REPLACE
?●:→?
Fig. 5. Application
(Record Type Concat)
C-EMPTY
C-STRONGL
C-EXT
(Strength Concat)
C-STRONGR
C-LATER
? ⊕ ★ ↔ ★
C-LEAVE
: ⊕ ? ↔ :
C-REPLACE
: ⊕ : ↔ :
Fig. 6. Concatenation
P-LABEL guesses a type A and uses the given parameter name . Rule P-RECORD handles nested record patterns. As a simple example, .
Application (Fig. 5). The judgement models function application: when a function expecting parameters receives an argument of type , it computes the remaining parameter type . This judgement assumes that entries in and appear in a convenient order, as record subtyping takes care of commutativity and optional entry insertion.
These rules directly reflect the behaviour of strengths outlined in §2.9. Rule A-EMPTY is straightforward. Rules A-WEAKSTRONG and A-OPTIONALSTRONG handle cases where a strong argument is supplied, thereby eliminating the parameter from the resulting type. Otherwise, the parameter remains in some form via rule A-EXT, where its resulting strength is determined by a strength-specific variant of the judgement, . For a required parameter, it remains required if it is provided an optional argument (rule A-LATER), and becomes optional when provided with a weak argument (rule A-SET). Finally, an optional parameter remains optional regardless of the argument's strength in rules A-LEAVE and A-REPLACE.
Concatenation (Fig. 6). The record concatenation judgement computes the resulting record type . As before, we assume that entries appear in a convenient order within and . Concatenation depends on record strength and is thus not commutative, as label order matters for shadowing and overwriting. Rule C-STRONGL always preserves a strong entry on the left; otherwise C-EXT combines the two strengths via : a strong entry on the right overwrites a weak one (C-STRONGR), an optional entry is overwritten (C-LATER) or ignored when the left entry is weak (C-LEAVE), and a weak entry replaces a matching weak entry (C-REPLACE).
3.3 Example
To illustrate how application interacts with subtyping, consider the partial application
which supplies only the first of two positional arguments (we assume simple arithmetic operators and omit uninteresting derivation details). To type it, subtyping first adds an optional entry for the missing second argument through S-EMPTY:
\boxed{\mathbf{T}}=\frac{\frac{\left\lfloor\_\right.\mathbf{?}\mathbf{N}\right\rfloor^{?}}{\varepsilon\leqslant\_\mathbf{?}\mathbf{N}}\frac{\mathrm{S-EMPTY}}{\cdots}}{\frac{\left\lfloor\_\right.\mathbf{?}\mathbf{N}\leqslant\_\mathbf{?}\mathbf{N},\_\mathbf{?}\mathbf{N}}{\left\{\_\right.\mathbf{?}\mathbf{N}\right\}\leqslant\left\{\_\right.\mathbf{?}\mathbf{N},\_\mathbf{?}\mathbf{N}\right\}}\frac{\mathrm{S-EXT}}{\mathrm{S-RECORD}}The application judgement then eliminates the first parameter but leaves the second one:
\boxed{\mathbf{A}}=\frac{\frac{\overline{\varepsilon\bullet\varepsilon\rightarrow\varepsilon}\mathrm{A-EMPTY}}{\_:\mathbf{N}\bullet\_\mathbf{?}\mathbf{N}\rightarrow\varepsilon}\mathrm{A-WEAKSTRONG}\quad\frac{\overline{\vdots\bullet?\rightarrow:}\mathrm{A-LATER}}{\_:\mathbf{N},\_:\mathbf{N}\bullet\_\mathbf{?}\mathbf{N},\_?\mathbf{N}\rightarrow\_\mathbf{:}\mathbf{N}}\mathrm{A-EXT}}Finally, rule T-APP combines the two, yielding a function that still expects the second argument:
\frac{\overline{\varepsilon\vdash\lambda\left\{\_ \diamond i_{0},\_ \diamond i_{1}\right\}.@.i_{0}-@.i_{1}:\left\{\_:\mathbb{N},\_:\mathbb{N}\right\}\rightarrow\mathbb{N}}{\varepsilon\vdash\left(\lambda\left\{\_ \diamond i_{0},\_ \diamond i_{1}\right\}.@.i_{0}-@.i_{1}\right)\left\{\_ =2\right\}:\left\{\_:\mathbb{N}\right\}\rightarrow\mathbb{N}}\begin{array}{c}\mathbf{T}-\mathrm{LAM}\\ \mathbf{T}\end{array}\begin{array}{c}\mathbf{A}\\ \mathbf{T}-\mathrm{APP}\end{array}The appendix contains further examples involving pattern separation and concatenation.
3.4 Evaluation
Fig. 7 presents the operational semantics: evaluates to under the evaluation environment . Many of the rules are routine; here we focus on the most interesting ones.
First, rule E-LAM evaluates lambdas into closures with an empty record of accumulated arguments. The current environment is captured inside the closure to preserve an important invariant: values (e.g. closures) are self-contained and do not depend on the surrounding scope. In rule E-APP, the accumulated arguments in are concatenated with the new arguments . The meta-notation ++ (also used in rule E-CONCAT) is analogous to the type-level concatenation relation; its complete definition is provided in the appendix. The resulting term remains well-typed, a property guaranteed in part by Lemma 3.6.
Closures are eliminated via rule E-FORCECLOSURE, which converts them into boxes. Here, the expand(c; ) operation destructures and renames entries according to the record pattern c. The rule then evaluates e under the captured environment extended with the arguments . Similarly, rule E-LETV performs a corresponding conversion to evaluate let-boundings.
Rule E-BOXR is the only rule that updates the evaluation environment. Specifically, the rule ignores the current environment , and evaluates under the environment . Rule E-BOX discards the environment for values, since values are self-contained. Rule E-ENV is the only rule where the evaluation environment is accessed, serving a dual role to that of rule E-BOXR.
Finally, rules E-PROJRECORD, E-MPROJRECORD, and E-DIFFRECORD handle the basic record operations. Auxiliary meta-operations proj, mproj, and diff behave straightforwardly; their full definitions are omitted for brevity and included in the appendix. Mechanically, these notations traverse from right to left to select or discard the designated entries.
3.5 Desirable Properties and Type Soundness
In this section, we demonstrate that our calculus enjoys several desirable properties, which facilitate reasoning about system behaviour, and we then prove type soundness and normalization.
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
(Operational Semantics)
\begin{aligned}&\frac{\mathrm{E-APPL}}{o\vdash e_{0}\longrightarrow e_{0}^{\prime}}\\&\frac{o\vdash e_{0}e_{1}\longrightarrow e_{0}^{\prime}e_{1}}{}\\&\frac{\mathrm{E-FORCE}}{o\vdash e\longrightarrow e^{\prime}}\\&\frac{o\vdash\mathrm{force}e\longrightarrow\mathrm{force}e^{\prime}}{\mathrm{E-BOXR}}\\&\frac{o_{1}\vdash e\longrightarrow e^{\prime}}{o_{0}\vdash\left\{o_{1}\right\}\blacktriangleright e\longrightarrow\left\{o_{1}\right\}\blacktriangleright e^{\prime}}\\&\frac{\mathrm{E-EXTL}}{o\vdash\left\{r\right\}\longrightarrow\left\{r^{\prime}\right\}}\\&\frac{o\vdash\left\{r,i\star e\right\}\longrightarrow\left\{r^{\prime},i\star e\right\}}{\mathrm{E-CONCATL}}\\&\frac{o\vdash e_{0}\longrightarrow e_{0}^{\prime}}{o\vdash e_{0}++e_{1}\longrightarrow e_{0}^{\prime}++e_{1}}\\&\frac{\mathrm{E-PROJ}}{o\vdash e\longrightarrow e^{\prime}}\\&\frac{\mathrm{proj}(o_{1};i)=v}{o_{0}\vdash\left\{o_{1}\right\}.i\longrightarrow v}\\&\frac{\mathrm{E-DIFF}}{o\vdash e\longrightarrow e^{\prime}}\\&\frac{\mathrm{diff}(o_{1};\overline{i_{j}})=o_{2}}{o_{0}\vdash\left\{o_{1}\right\}\backslash\left\{\overline{i_{j}}\right\}\longrightarrow\left\{o_{2}\right\}}\\&\frac{\mathrm{E-LETV}}{\mathrm{expand}(t;v)=o_{1}}\\&\frac{o_{0}\vdash\mathrm{let}t=v\mathrm{in}e\longrightarrow\left\{o_{0},o_{1}\right\}\blacktriangleright e}\end{aligned}Fig. 7. Operational semantics
Subtyping. First, we prove that subtyping is reflexive and transitive:
Lemma 3.1 (Subtyping reflexivity). for all A.
Lemma 3.2 (Subtyping transitivity). If and , then .
Record subtyping is preserved when entries are appended; the condition ensures that S-EMPTY has not added optional entries on the left-hand side for a name that appears in :
Lemma 3.3 (Record subtyping appending). If , , and , then , , .
Moreover, subtyping on the environment is admissible:
Lemma 3.4 (Environment subtyping). If with , and , then .
Intuitively, this holds since the only way to access the environment is via @ through rule T-ENV, and we can always apply the subsumption rule (T-SUB) and the record subtyping rule (S-RECORD) immediately after. The second hypothesis ensures the subtyping relationship can be maintained using Lemma 3.3 even when new bindings are introduced.
Concatenation. The following lemma establishes the associativity property of concatenation. For concision, we often embed record operators directly within other relations. For instance, we write , which implies there exists such that and .
Lemma 3.5 (Associativity of ). if and only if .
Application and record concatenation. The next lemma establishes an associativity-like property between application and concatenation. Intuitively, it shows that given an initial , consecutively applying it first to and then to yields the same result as first concatenating and and then applying to the result.
Lemma 3.6 (Associativity of • over ⊕). if and only if .
Type soundness. First, we prove that the operational semantics enjoy determinacy:
Theorem 3.7 (Determinacy). If and then .
We then establish type soundness for through progress and preservation.
Theorem 3.8 (Preservation). Given with , if , and , then .
Theorem 3.9 (Progress). Given with , if , then either is a value, or there exists such that .
Normalization. Additionally, since our reduction is non-standard, we also formally prove its normalization property. The proof proceeds via a logical relation [Tait 1967]:
In the function case, we quantify over record types whose application leaves only entries of optional strength ( ), and over an argument value which satisfies the relation under any well-typed environment. Terms of record types are required to reduce to concrete records whose entries all satisfy the relation. The quantifier case is straightforward with predicative polymorphism. The most interesting aspect of these proofs is that we avoid substitutions by assuming the first-class environment satisfies the relation. We prove the fundamental theorem and then normalization:
Theorem 3.10 (Fundamental). Given with , if then .
Theorem 3.11 (Normalization). If then terminates.
3.6 Syntax-Directed Typing
The declarative typing rules are not syntax-directed: subsumption (T-SUB) may be applied anywhere, and quantifiers are instantiated implicitly through subtyping. In this section we present a syntax-directed variant that is sound and complete with respect to the declarative system. Full algorithmic type inference is outside the scope of this paper, but the syntax-directed rules show how our features can be handled without guessing where to apply subsumption. Selected rules are given in Fig. 8; the full set of typing and updated auxiliary judgement rules can be found in the appendix.
(Syntax-Directed Typing and Instantiation)
ST-FORCE
ST-INSTANTIATE
Fig. 8. Syntax-directed typing
The usual approach of instantiating quantifiers eagerly at variables and re-generalizing at lets does not fit our language: variables are projections out of a first-class environment, types are
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
higher-rank, and we generalize at abstractions rather than lets. We therefore instantiate lazily, in the elimination rules. In rule ST-FORCE, for instance, the first hypothesis accepts any number of quantifiers, which are instantiated in the conclusion. Without subtyping to discard optional entries (S-EMPTY), may be non-empty, so the second hypothesis checks its strengths instead. This hypothesis also suggests an elaboration that inserts force automatically: whenever a term of type with is used at type A, the elaboration wraps it in force, so that programmers need not write it explicitly. Such an elaboration fits naturally with bidirectional typing [Dunfield and Krishnaswami 2021], where the expected type is available in checking mode; we leave this to future work. The double-colon hypothesis invokes a helper judgement (ST-INstantiate) for types such as . a, in which case we instantiate it with any type. Such types can exist as function arguments. Finally, auxiliary judgements such as pattern separation, application, and concatenation also have syntax-directed versions, as used in ST-LET.
We prove that our syntax-directed typing is sound and complete:
Theorem 3.12 (Soundness). If then .
Theorem 3.13 (Completeness). If with , then there exists such that and .
3.7 Translating the Lambda Calculus
To demonstrate that the use of explicit environments preserves the semantics of the substitution model, we present a translation from the simply typed lambda calculus (STLC) to . The syntax and semantics of STLC are standard and given in the appendix.
Translations. The translation of types, environments, and terms from STLC to is defined below. We assume STLC uses its own mechanism to ensure variable freshness, thus we utilize a translation environment to track the variable mapping between the two calculi. (Our mechanization formalises STLC using the locally nameless representation [Charguéraud 2011].)
The translation rules are then largely straightforward. STLC lambdas are mapped to lambdas that have a record pattern with a single positional argument, and STLC applications are mapped to force expressions of applications with the argument passed positionally.
Simulation. First, we prove that typing is preserved under translation:
Theorem 3.14 (Preservation of typing). If , then .
Relating the evaluation behaviour of the two calculi is slightly more involved. We utilize a term approximation relation , which states that an STLC term is approximated by a term under an approximation environment . We defer the details to the appendix. We establish the correspondence of semantics between the two calculi:
Theorem 3.15 (Correspondence of semantics). if and only if .
4 Extension: References
In this section, we extend with mutable references. This particular extension serves two primary purposes. First, it introduces side-effects, under which it is critical to have deterministic evaluation behaviour in the presence of partial application, optional arguments, and overwriting. Second, consistent with our paradigm of using records to formalise various language constructs, we leverage records to model stores that map reference locations to their values.
Syntax and semantics. Fig. 9 presents the extended syntax, typing, and operational semantics. Congruence reduction rules and syntax-directed typing are omitted for space but can be found in the appendix. Types now include the reference type Ref A. Terms include locations l (treated as a form of label), reference allocation ref e, dereferencing !e, and assignment . Accordingly, values are also extended to include locations. Moreover, we use the record value o as a store that maps locations to values, and its corresponding type as the store typing. A store type is well-formed, written , when all its entries have strength (:) and all locations are unique.
The extended subtyping and typing are standard. Subtyping of references is invariant. The typing judgement now incorporates a store type using a record type. Rule T-LOC types locations as references to the type specified in the store.
The evaluation judgement is also extended to thread the store through each step. Rule E-REFV allocates a fresh name in the store. (In the mechanization, the operational semantics maintain determinacy by picking the fresh name to be the maximal variable index in the store plus one.) Rule E-DEREFLOC projects the corresponding entry out of the store. Finally, rule E-SET leverages the overwriting behaviour of record concatenation to update the corresponding store entry.
Generalization and the value restriction. It may seem surprising that we did not modify any of the original typing rules. In systems with polymorphism and generalization, it is well-known that adding mutable state can easily yield type unsoundness. As an example, consider the program on the right. Naive let-generalization will assign x a polymorphic type . The type variable a is then instantiated to on line 2, and to on line 3, allowing the program to type-check. However,
let x = ref (λ{ i }. i) in let { } = (x := (λ{ i }. i + 1)) in force !x { i = true }
the program fails at runtime, as it applies a function expecting a natural number to a boolean.
To preserve safety, a standard remedy is the value restriction [Wright 1995], which limits let-generalization to syntactic values. Applying this restriction would prevent x from being generalized, and thus the program fails to type-check. While this approach guarantees soundness, it doesn’t integrate very nicely with our calculus: let-generalization introduces universal quantifiers at the topmost level of a binding, while we often want to localize polymorphism within individual record fields, rather than enforcing top-level quantifiers over an entire record.
We therefore adapt the approach recently proposed by Dolan [2024], which performs generalization at functions (specifically rules T-LAM and T-CLOSURE in our case), rather than let-boundings. This approach can be considered a more fine-grained variant of the value restriction. It restores type soundness; for example, in the program above x can be typed either with Ref ( ) or with a monotype, causing a type error in either case. Moreover, the approach also increases
(Subtyping and Typing)
S-REF
T-LOC
T-REF
T-SET
Ref Ref A
(Operational Semantics)
E-REFV
E-DEREFLOC
E-SET
Fig. 9. Extension with references (selected rules)
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
typeability, as it allows the individual components of a non-value compound expression to generalize independently. In our calculus, this design naturally facilitates the construction of records with polymorphic fields, e.g. let in e assigns type . We also extend this approach to T-APP: when the argument is polymorphic over the same type variables as the function, the application keeps those quantifiers rather than instantiating them. This is useful for partial applications that do not require particular instantiations for some quantifiers, and it is sound here because reduction (and thus reference allocation) does not occur until a force is encountered.
Type soundness. We have proven the determinacy, progress, and preservation theorems for the extended semantics, where the theorems are now adapted to account for the presence of stores; we omit their statements for space. The syntax-directed system likewise extends to references and remains sound and complete.
5 Mechanization and Implementation
Mechanization. We have mechanized using the Lean 4 proof assistant [Moura and Ullrich 2021], covering all semantics and theorems. Table 1 summarizes the statistics. By using explicit environments, we avoid the term-level binding complications described in §2.1, allowing labels and locations to be represented simply as natural numbers. However, without explicit type environments, we adopt the locally nameless representation [Charguéraud 2011] for type variables.
Most of the proofs proceeded without significant difficulty. One particular challenge in a few cases, such as Lemma 3.2, was to show that the induction used to prove them was well-founded. This arose as Lean has proof irrelevance: since Lean treats all propositions of the same type as equal, the depth of a derivation cannot be used directly in termination measures. We circumvented this limitation by defining versions of subtyping and multi-step evaluation that are explicitly indexed by their derivation depth, and using these numerical indices as well-founded measures.
Table 1. Code stats of mechanization and implementation
| Component | LOC | Decls |
|---|---|---|
| Type Soundness | 16260 | 773 |
| STLC Correspondence | 1366 | 65 |
| Big-Step Equivalence | 396 | 10 |
| Normalization | 5932 | 93 |
| Syntax-Directed Typing | 4695 | 11 |
| Implementation | 934 | 48 |
| Total | 29619 | 1000 |
Implementation. Since one of our motivations for using first-class environments is to close the gap between specification and implementation identified by Tan and Oliveira [2024], we have implemented an interpreter and verified it against our operational semantics. Because the extended supports general references, and it's known that references can encode recursion (via Landin's knot [Landin 1964]), well-typed programs are not guaranteed to terminate. We thus leverage Lean's partial_fixpoint feature and the option monad to define our evaluation function eval. This frees us from providing a termination proof for eval, while still allowing us to formally reason about it. For proof purposes, Lean assigns none to non-terminating inputs.
We then prove the equivalence of the operational semantics and the evaluation function eval. The first clause of the following theorem expresses that for terminating inputs, the operational semantics and eval agree. The second clause states that for well-typed inputs, eval yields none precisely when there are infinite reduction steps (denoted by ).
Theorem 5.1 (Interpreter correctness).
- if and only if eval o e .
https://lean-lang.org/doc/reference/4.33.0/Definitions/Recursive-Definitions/#partial-fixpoint
- Given with , and with , if , then if and only if eval e = none.
We prove this theorem by using the transitivity of equivalence, introducing an intermediate big-step operational semantics for (whose full rules are provided in the appendix), which is proven equivalent to both the interpreter's eval function and the small-step operational semantics.
6 Discussion
6.1 The Design Space
Function application paradigms encompass a broad design space. In this section, we examine how these various features are supported across programming languages. The selected languages are (1) Python (dynamically typed), (2) TypeScript (gradually typed), (3) Swift, (4) OCaml, (5) Scala (all statically typed), and (6) Lean 4 (dependently typed). While many more languages exist, these languages offer a diverse and representative spectrum of modern language design decisions. We summarize the comparison in Table 2:
| Python | Typescript | Swift | OCaml | Scala | Lean 4 | ||
|---|---|---|---|---|---|---|---|
| named arguments | f(a=x) | f({a: x}) | f(a: x) | f ~a:x | f(a = x) | f (a := x) | f {a=x} |
| first-class arguments | ✓ | ✕ | ✕ | ✕ | ✕ | ✓ | |
| optional arguments | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| distinct args and params | ✕ | ✓ | ✓ | ✓ | ✕ | ✓ | |
| commutative arguments | ✓ | ✕ | ✓ | ✓ | |||
| partial application | ✕ | ✕ | ✕ | ✓ | ✓ | ✓ | ✓ |
Table 2. A comparison table of languages with named arguments (with explained in §6.1)
All languages listed in the table offer some degree of support for named arguments. Although TypeScript lacks native support, simulating this behaviour by passing a single object is a widespread idiom in its community; we thus record ticks for both named and first-class arguments. Statically typed languages often support named arguments through elaboration, while dynamically typed ones typically resolve them by matching labels against function parameters at runtime.
We use first-class arguments to mean that a function's arguments can be stored within a data structure and subsequently supplied to a function call. For example, in Python, the example in §2.3 can be rewritten using the dictionary unpacking operator **:
transaction = { amount: 1000, "from_account": "Alice", "to_account": "Bob" } transfer_funds(**transaction)
Optional type checkers for Python can type such keyword arguments with a record type [Magiera 2022]. inherently supports first-class arguments by modelling arguments as records. On the other hand, this feature is rarely supported among statically typed languages.
All listed languages support certain forms of optional arguments that can be omitted at call sites. This unanimous adoption stems partly from our focus on languages with named arguments, which provide the parameter disambiguation necessary to make optional arguments viable. A few languages do not require default values for optional arguments. In TypeScript, for instance, an omitted argument defaults to undefined, and its presence must be checked by e.g. c === undefined.
In both Swift and OCaml, distinct argument labels and parameter names are specified within the function definition. TypeScript mimics this behaviour via property-renaming syntax during object destructuring. In Lean , this feature emerges as a consequence of type equivalence, where the desired argument label can be set by annotating the function with a new type.
While language-specific workarounds can often simulate missing capabilities, our evaluation mostly focuses on native support, acknowledging that a simple binary classification can occasionally obscure these underlying nuances.
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
Commutative arguments are typical among named arguments, though exceptions like Swift exist. Positional arguments cannot commute with themselves, as their order determines their identity. It remains to ask whether positional arguments can commute with named ones. In Python , positional arguments must always precede named arguments. Scala allows a positional argument to follow a named one, if the entire sequence up to that point aligns perfectly with the definition-site order. OCaml is more flexible and allows positional arguments to commute with named arguments, as long as a positional argument appears last to mark the end of application. Lastly, as a dependently typed system, Lean 4 permits argument commutation provided that the permutation does not violate any underlying type dependencies. However, while these languages allow named arguments to be passed commutatively at the call site, they do not support structural commutativity. For example, if a higher-order function g expects an argument of type { name:String, age:Int } → Int, passing a function f : { age: Int, name: String } → Int results in a type error. Conversely, it type-checks in , which natively supports commutativity.
With partial application, applying a function to a subset of its arguments results in a new function taking the remaining parameters. Unlike traditional currying, which is constrained by strict sequential evaluation, general partial application allows a function to be partially applied to an arbitrary subset of arguments. Scala achieves this via wildcard placeholder syntax: transfer_from_alice = transfer_funds(_:Int, "Alice", _:String). Nevertheless, Scala requires programmers to explicitly mark each unapplied parameter with _. This mechanism also replaces the original parameter names with compiler-generated names (v1, v2, ...), obscuring the purpose of the remaining arguments. As discussed in §2.7, partial application interacts with optional arguments. While OCaml requires a subsequent positional argument after optional ones, Scala and Lean 4 automatically fill in missing optional arguments with their default values during compilation.
6.2 Discussion: Broader Applications
In this section, we broaden our scope to examine how various components of our design can be helpful in alternative contexts, highlighting the underlying principles of our design; the appendix discusses further applications.
Safe interface upgrades with optional subtyping. Record-like data structures are widely used to describe software interfaces, which naturally evolve over time. As a simple example, consider the user profile interface (a) in Fig. 10, which specifies a profile sent from a client to a server:
(a) a profile interface # (b) upgraded interface # (c) safe upgraded interface
type profile = { bio : text theme_color : num } bio : text theme_color : num + dark_mode : bool } + dark_mode : opt bool }
Fig. 10. Interface upgrades (specified with +)
A new software release may introduce additional features and consequently update the interface. For example, interface (b) upgrades the profile interface with a dark_mode field to specify whether the server should render a dark theme. However, legacy clients that have not upgraded will now send profiles lacking this field, creating a type mismatch and causing runtime errors. In this context, an upgrade is considered safe if a client sending data according to the old format does not cause a failure when the server expects the new format (and vice versa).
To resolve this challenge, the interface description language Candid [DFINITY 2026a] requires that an interface for inbound data (i.e. data sent from the client to the server) may only be replaced by a supertype (e.g. fewer fields); therefore, the upgrade (b) is rejected. On the other hand, Candid permits a record subtyping rule that is “unusual but necessary in practice” [DFINITY 2026b], where new fields are allowed in the supertype as long as they are optional. Under this rule, interface (a) is considered a subtype of (c), where the newly added dark_mode field has type opt bool. Thus interface (c) is accepted as a safe upgraded interface. We note that this use of optional types is similar to ours, and the subtyping rule corresponds to the extra right entries in our S-EMPTY rule.
Interestingly, Candid combines the standard record width subtyping with the above subtyping rule for optionals, which leads to surprising consequences. Specifically, via record width subtyping, interface (a) is a subtype of { bio : text }, which removed the theme_color field. Via subtyping for optionals, { bio : text } is a subtype of { bio : text, theme_color : opt string }. It follows, via subtyping transitivity, that (a) is a subtype of { bio : text, theme_color : opt string }; effectively, this changes the type of theme_color from nat to opt string. However, if one were to compare nat and opt string directly, subtyping would fail. Since subtyping transitivity is crucial for supporting sequences of upgrades, Candid's subtyping tolerates such type mismatches at runtime, yielding null values for the affected fields. On the other hand, our system omits the record width subtyping rule entirely, and thus this specific issue does not arise. Specifically, width subtyping effectively allows a function to accept extraneous arguments (e.g. sub { name = "Alice"} that serve no purpose. Such applications are disallowed; instead, a programmer can use record projection to extract the desired fields from an argument before passing it to a function.
Packaging with overwritable fields. The Nix language is a functional domain-specific language that powers the Nix packaging system [Dolstra and The Nix contributors 2026]. Nix evaluates expressions to create derivations, which describe how to build reproducible packages. For example, consider a package recipe defined as a function of its dependencies, including an openssl argument:
let app = { stdenv, openssl } : stdenv.mkDerivation { name = "app"; buildInputs = [ openssl ]; };
We can instantiate this recipe using the callPackage function, providing an attribute set that explicitly binds stdenv, as well as the openssl argument to the openssl_1_1 package:
myApp = pkgs.callPackage app { stdenv = pkgs.stdenv; openssl = pkgs.openssl_1_1; };
More interestingly, callPackage allows arguments to be customized after the fact using a derivation's override function. For example, even after myApp has been instantiated, we can override its openssl argument with a new value to update the package to OpenSSL 3.0:
mySecuredApp = myApp.override { openssl = pkgs.openssl_3; };
Here, myApp.override overrides the openssl argument originally supplied by callPackage, producing a new derivation with the exact same arguments as myApp except for the updated openssl dependency. Note that since Nix is functional, this does not mutate the original package. This style of overriding is made possible by Nix's evaluation strategy, which evaluates expressions to construct a derivation graph but defers the actual compilation and building of binaries until a build is explicitly requested (e.g. via nix-build). This behaviour aligns with our overwritable arguments feature, which allows a function's arguments to be overwritten even after the function has been applied, and the evaluation of a function is deferred until it is explicitly forced.
7 Related Work
We have discussed comparisons to various formalisms and languages throughout the paper. While many production languages feature forms of named and optional arguments, their designs are mostly described informally [Flatt and Barzilay 2009; Rytz and Odersky 2010]. Formally, Garrigue [2001] presented typing rules for labelled and optional arguments for OCaml, noting that the application rule becomes complex because it “integrates all the commuting and discarding machinery”. More recently, Sun and Oliveira [2025] modelled named arguments using intersection types and optional
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
arguments using union types; they identified a tension with record width subtyping that closely mirrors the Candid issue discussed in §6.2.
One recent exploration of first-class environments is by Tan and Oliveira [2024]. Our approach differs from theirs in several significant ways. First, their calculus uses de Bruijn indices, and thus environments are not commutative. Moreover, they explicitly disallow lookups from environments with duplicate labels. Further, lacks support for polymorphism or function application paradigms.
Row calculi have a rich history in the literature. Most relevant to our setting are Leijen [2005], which supports duplicate labels, and Rémy [1994], which allows existing labels to be overwritten. Furthermore, Osinski [2006] introduced a record concatenation operator (&) that permits duplicate labels only when they have the same type, in which case the value of the field in the second operand is selected (similarly to our shadowing behaviour). CDuce [Benzaken et al. 2003] supports optional fields in record types and distinguishes open record types, which admit extra fields, from closed ones. Read this way, records are closed: a supertype may only add optional fields. For a recent and comprehensive overview of the design space of record calculi, we refer the reader to Morris and McKinna [2019].
Data Availability Statement
The Lean 4 development accompanying this paper is provided in the supplementary materials. It contains the mechanized proofs of all stated lemmas and theorems, as well as the code of the interpreter and the proof of its equivalence with the operational semantics.
References
M. Abadi, L. Cardelli, P.-L. Curien, and J.-J. Levy. 1989. Explicit substitutions. In Proceedings of the 17th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (San Francisco, California, USA) (POPL '90). Association for Computing Machinery, New York, NY, USA, 31–46. doi:10.1145/96709.96712
Véronique Benzaken, Giuseppe Castagna, and Alain Frisch. 2003. CDuce: an XML-centric general-purpose language. In Proceedings of the Eighth ACM SIGPLAN International Conference on Functional Programming (Uppsala, Sweden) (ICFP '03). Association for Computing Machinery, New York, NY, USA, 51–63. doi:10.1145/944705.944711
Malgorzata Biernacka and Olivier Danvy. 2007. A concrete framework for environment machines. ACM Trans. Comput. Logic 9, 1 (Dec. 2007), 6–es. doi:10.1145/1297658.1297664
Dariusz Biernacki, Maciej Piróg, Piotr Polesiuk, and Filip Sieczkowski. 2017. Handle with care: relational interpretation of algebraic effects and handlers. Proc. ACM Program. Lang. 2, POPL, Article 8 (Dec. 2017), 30 pages. doi:10.1145/3158096
Luca Cardelli. 1997. Program fragments, linking, and modularization. In Proceedings of the 24th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (Paris, France) (POPL '97). Association for Computing Machinery, New York, NY, USA, 266–277. doi:10.1145/263699.263735
Arthur Charguéraud. 2011. The Locally Nameless Representation. Journal of Automated Reasoning 49, 3 (May 2011), 363–408. doi:10.1007/s10817-011-9225-2
Alonzo Church. 1941. The Calculi of Lambda-Conversion. Number 6 in Annals of Mathematics Studies. Princeton University Press, Princeton, NJ, USA.
P.-L. Curien. 1991. An abstract framework for environment machines. Theoretical Computer Science 82, 2 (May 1991), 389–402. doi:10.1016/0304-3975(91)90230-Y
Leijen Daan. 2014. Koka: Programming with Row Polymorphic Effect Types. Electronic Proceedings in Theoretical Computer Science 153 (06 2014), 100–126. doi:10.4204/eptcs.153.8
Nicolaas Govert de Bruijn. 1972. Lambda calculus notation with nameless dummies, a tool for automatic formula manipulation, with application to the Church-Rosser theorem. Indagationes Mathematicae (Proceedings) 75, 5 (1972), 381–392. doi:10.1016/1385-7258(72)90034-0
DFINITY. 2026a. Candid. https://github.com/dfinity/candid
DFINITY. 2026b. Candid Specification: Upgrading and Subtyping. https://github.com/dfinity/candid/blob/d24fb18fadaabbe56b3abd0bb597e49117ca4bfa/spec/Candid.md#upgrading-and-subtyping
Stephen Dolan. 2024. Rethinking the Value Restriction. Higher-order, Typed, Inferred, Strict: ML Family Workshop 2024. Eelco Dolstra and The Nix contributors. 2026. Nix. https://github.com/NixOS/nix
Jana Dunfield and Neel Krishnaswami. 2021. Bidirectional Typing. ACM Comput. Surv. 54, 5, Article 98 (May 2021), 38 pages. doi:10.1145/3450952
Matthew Flatt and Eli Barzilay. 2009. Keyword and optional arguments in PLT Scheme. In Proceedings of the Tenth Workshop on Scheme and Functional Programming.
Jacques Garrigue. 2001. Labeled and optional arguments for Objective Caml. In JSSST Workshop on Programming and Programming Languages, Kameoka, Japan.
Benedict R Gaster and Mark P Jones. 1996. A polymorphic type system for extensible records and variants. Technical Report. Technical Report NOTTCS-TR-96-3, Department of Computer Science, University of Nottingham.
D. Gelernter, S. Jagannathan, and T. London. 1987. Environments as first class objects. In Proceedings of the 14th ACM SIGACT-SIGPLAN Symposium on Principles of Programming Languages (Munich, West Germany) (POPL '87). Association for Computing Machinery, New York, NY, USA, 98–110. doi:10.1145/41625.41634
Mark P. Jones. 1994. Qualified Types: Theory and Practice. Cambridge University Press, Cambridge, UK. doi:10.1017/CBO9780511663086
P. J. Landin. 1964. The Mechanical Evaluation of Expressions. Comput. J. 6, 4 (1964), 308–320. doi:10.1093/COMJNL/6.4.308
Mickaël Laurent, Pierre Donat-Bouillud, Filip Krikava, and Jan Vitek. 2026. Revisiting Row Polymorphism for Set-Theoretic Types. Proc. ACM Program. Lang. 10, OOPSLA2, Article 373 (Oct. 2026), 27 pages. doi:10.1145/3839505
Daan Leijen. 2005. Extensible records with scoped labels. In Proceedings of the 2005 Symposium on Trends in Functional Programming (TFP'05), Tallin, Estonia. https://www.microsoft.com/en-us/research/publication/extensible-records-with-scoped-labels/
Paul Blain Levy. 2001. Call-By-Push-Value. Ph.D. Dissertation. University of London.
Paul Blain Levy. 2006. Call-by-push-value: Decomposing call-by-value and call-by-name. Higher Order Symbol. Comput. 19, 4 (Dec. 2006), 377–414. doi:10.1007/s10990-006-0480-6
Franek Magiera. 2022. PEP 692 – Using TypedDict for more precise **kwargs typing. Python Enhancement Proposal. https://peps.python.org/pep-0692/
Mark Samuel Miller. 2006. Robust composition: towards a unified approach to access control and concurrency control. Ph.D. Dissertation. Johns Hopkins University, Baltimore, MD, USA. Advisor(s) Shapiro, Jonathan S. AAI3245526.
Mark S. Miller, Chip Morningstar, and Bill Frantz. 2000. Capability-Based Financial Instruments. In Proceedings of the 4th International Conference on Financial Cryptography (FC '00). Springer-Verlag, Berlin, Heidelberg, 349–378.
J. Garrett Morris and James McKinna. 2019. Abstracting extensible data types: or, rows by any other name. Proc. ACM Program. Lang. 3, POPL, Article 12 (Jan. 2019), 28 pages. doi:10.1145/3290325
Leonardo de Moura and Sebastian Ullrich. 2021. The Lean 4 Theorem Prover and Programming Language. In Automated Deduction – CADE 28: 28th International Conference on Automated Deduction, Virtual Event, July 12–15, 2021, Proceedings. Springer-Verlag, Berlin, Heidelberg, 625–635. doi:10.1007/978-3-030-79876-5_37
Edward Osinski. 2006. A polymorphic type system and compilation scheme for record concatenation. Ph. D. Dissertation. USA. Advisor(s) Goldberg, Benjamin F. AAI3221986.
Gordon D. Plotkin and John Power. 2001. Adequacy for Algebraic Effects. In Proceedings of the 4th International Conference on Foundations of Software Science and Computation Structures (FoSSaCS '01). Springer-Verlag, Berlin, Heidelberg, 1–24.
Gordon D. Plotkin and Matija Pretnar. 2013. Handling Algebraic Effects. Logical Methods in Computer Science 9, 4 (2013). doi:10.2168/LMCS-9(4:23)2013
Didier Rémy. 1994. Type inference for records in natural extension of ML. MIT Press, Cambridge, MA, USA, 67–95.
Lukas Rytz and Martin Odersky. 2010. Named and default arguments for polymorphic object-oriented languages: a discussion on the design implemented in the Scala language. In Proceedings of the 2010 ACM Symposium on Applied Computing (Sierre, Switzerland) (SAC '10). Association for Computing Machinery, New York, NY, USA, 2090–2095. doi:10.1145/1774088.1774529
Masahiko Sato, Takafumi Sakurai, and Rod Burstall. 2001. Explicit Environments. Fundamenta Informaticae 45, 1–2 (Jan. 2001), 79–115.
Yaozhu Sun and Bruno C. d. S. Oliveira. 2025. Named Arguments as Intersections, Optional Arguments as Unions. In Programming Languages and Systems: 34th European Symposium on Programming, ESOP 2025, Held as Part of the International Joint Conferences on Theory and Practice of Software, ETAPS 2025, Hamilton, ON, Canada, May 3–8, 2025, Proceedings, Part II (Hamilton, ON, Canada). Springer-Verlag, Berlin, Heidelberg, 347–373. doi:10.1007/978-3-031-91121-7_14
W. W. Tait. 1967. Intensional Interpretations of Functionals of Finite Type I. The Journal of Symbolic Logic 32, 2 (1967), 198–212. doi:10.2307/2271658
Jinhao Tan and Bruno C. d. S. Oliveira. 2024. A Case for First-Class Environments. Proc. ACM Program. Lang. 8, OOPSLA2, Article 360 (Oct. 2024), 30 pages. doi:10.1145/3689800
Mitchell Wand. 1987. Complete Type Inference for Simple Objects. In Proceedings of the Symposium on Logic in Computer Science (LICS '87), Ithaca, New York, USA, June 22-25, 1987. IEEE Computer Society, 37–44.
Keith Wansbrough and Simon Peyton Jones. 1999. Once upon a polymorphic type. In Proceedings of the 26th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (San Antonio, Texas, USA) (POPL '99). Association for
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
Computing Machinery, New York, NY, USA, 15–28. doi:10.1145/292540.292545
Andrew K. Wright. 1995. Simple imperative polymorphism. Lisp Symb. Comput. 8, 4 (Dec. 1995), 343–355. doi:10.1007/BF01018828
A More Discussions
A.1 Broader Applications
Typed XML documents with optional values. CDuce [Benzaken et al. 2003] is a typed functional language targeted at XML applications, in which the attributes of an XML element form a record. Since XML attributes are often optional, a record type can mark a field as optional, e.g. { kind =? String }, as with our optional values. CDuce distinguishes open record types, which admit new fields, from closed ones, which do not. Since subtyping in CDuce is defined as set inclusion, width subtyping requires an open supertype, while a closed type may only add optional fields. Read this way, records are closed. Under the open reading, the type { bio : text } from the Candid example in §6.2 admits a theme_color field of any type, and is therefore not a subtype of { bio : text, theme_color : opt string }. CDuce records have unique labels, however; extending with open records would require care, as the additional fields of an open record must not shadow existing ones.
Masking effects with optionals. Optional values emerge naturally in the presence of scoped labels. In particular, our formulation of optional values is closely related to the mask (also called inject or lift) operation found in algebraic effect handlers [Plotkin and Power 2001; Plotkin and Pretnar 2013] when effects are represented as scoped labels [Biernacki et al. 2017; Daan 2014]. In such systems, the effect type system tracks effect operations performed within an expression, and handlers eliminate these effects, with operations being handled dynamically by default with the innermost enclosing handler. If a developer intends for an effect to be handled by the second innermost handler instead, they can explicitly mask the innermost handler. For instance, mask<print> (print()) carries the duplicate effects {print, print}, though the first print label does not correspond to an actual operation, and print is then handled by the second innermost handler.
Presence types with strength subtyping. Consider a function eq : ∀a. { _ : a, _ : a } → bool, which takes two arguments of the same type and returns a boolean result. Assume we have two terms: alice : { name : String, age : Int } and bob : { name : String, age ? Int }. In a system without subtyping, the application (eq alice bob) would be rejected as the type variable a cannot be instantiated to match both arguments. Fortunately, via the subtyping rule S-LT, we can also type alice : { name : String, age ? Int }. Consequently, (eq { alice, bob }) type-checks successfully by instantiating a with { name : String, age ? Int }.
This approach is reminiscent of record calculi where labels have presence types [Rémy 1994]. In such a system, one can write alice : { name : pre(String), age : pre(Int); abs } and bob : { name : pre(String); abs }, where "abs" after ";" is a "template" type for all absent fields. However, Rémy [1994] noted a limitation of the calculus: the expression (eq { alice, bob }) fails to type-check as pre(Int) cannot be unified with abs. (The issue is also known as the poisoning problem [Wansbrough and Peyton Jones 1999], where type information from one expression pollutes another, here, via the presence of the abs field.) To address this, Rémy [1994] discussed an extension featuring a subtyping relation pre ≤ abs, which directly mirrors our subtyping rule S-LT.
A.2 Extensions
This section explores several potential extensions to our design.
Variadic arguments. Another common paradigm for function application is variadic arguments (or variable-length arguments), If the arguments are homogeneous, this feature can be considered as passing a list. More interestingly, in dynamically typed languages like Python, we can pass a variable number of arguments of different types, as demonstrated in the program on
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
the right. Here, display_info first takes name, and then a variable number of named arguments via kwargs and simply prints each key-value pair. We can then call def display_info(name, **kwargs):
for key, value in kwargs.items():
print(f"{key}:_{value}")
it like this: display_info(name="Alice", age=2, is_logged_in=True). In Python, varying named arguments can only be at the tail of a function.
Intuitively, this feature aligns well with row polymorphism featuring a polymorphic tail [Wand 1987]. Specifically, we can define a function with type . , where t represents a row variable, capturing all remaining arguments passed to the function. Laurent et al. [2026] realize this idea for R with set-theoretic types, encoding argument lists as records whose tail is closed, open, or a row variable that captures the arguments of the ellipsis parameter (...) and can be forwarded to another call.
While promising, in the presence of duplicated labels, this design is most effective when paired with qualified types [Jones 1994] to enforce constraints on the tail. For example, consider using the name variable within the body of the function above. If the tail t does not contain name, the variable clearly refers to the first parameter. However, if t is instantiated with a record that also contains a name label, it shadows the first parameter. As a result, the behaviour of the function depends on the instantiation of t. To prevent this ambiguity, a constraint such as (name t) can be introduced into the function type signature [Gaster and Jones 1996], which restricts t from being instantiated with any record containing a name label, thereby ensuring deterministic behaviour (see Morris and McKinna [2019] for more general row theories). We leave the exploration of this approach to future work.
Dependent default parameters. Dependent default parameters are evaluated at call-time and can refer to previously declared parameters. For example, we can define a JavaScript function: function add(x, y, z = x + y) { return z; }. This feature is, however, not widely supported among programming languages, especially those (e.g. OCaml) that do not guarantee a strict left-to-right evaluation order for function arguments. In Scala, this behaviour can be encoded via currying: def add(x:Int, y:Int)(z:Int = x + y): Int = z. We can achieve a similar encoding in our calculus: . , and calling this requires two forces.
Type components. Another potential extension is to include type components within records, thereby enabling System F-style type abstractions and applications. This extension on its own should be straightforward. On the other hand, we may want to allow subsequent fields to depend on earlier type components in the record, which approaches OCaml-style modules. In either case, it may be more practical to erase types before evaluation. We leave this investigation to future work.
B Additional Typing Examples
This section presents two further typing derivations. As before, we omit uninteresting derivation details.
Let-binding with pattern separation. Consider the following let-binding, whose pattern lists its labels in a different order from the record it destructures:
To type this example, subtyping first permutes the entries of the record type through S-EXT, so that they follow the order of the pattern:
\boxed{\mathbf{B}}=\frac{\frac{\frac{\left\lfloor\varepsilon\right\rfloor^{?}}{\varepsilon\leqslant\varepsilon}\text{S-EMPTY}}{\frac{i_{j}:\mathbb{N}\leqslant i_{j}:\mathbb{N}}{\quad}\cdots\quad\text{S-EXT}}{\frac{i_{k}:\mathbb{N},i_{j}:\mathbb{N}\leqslant i_{j}:\mathbb{N},i_{k}:\mathbb{N}}{\quad}\frac{\cdots}{\text{S-EXT}}}{\frac{\left\{i_{k}:\mathbb{N},i_{j}:\mathbb{N}\right\}\leqslant\left\{i_{j}:\mathbb{N},i_{k}:\mathbb{N}\right\}}{\quad}\text{S-RECORD}}}{\varepsilon;\varepsilon\vdash\left\{i_{k}:3,i_{j}:5\right\}:\left\{i_{k}:\mathbb{N},i_{j}:\mathbb{N}\right\}}\text{T-RECORD}}\quad\text{T-SUB}Pattern separation then splits the pattern into the type of the record it destructures and the parameter names it binds:
\boxed{\mathbf{P}}=\frac{\frac{\overline{\varepsilon:\varepsilon\odot\varepsilon}^{\mathrm{P-EMPTY}}\quad\overline{i_{j}:\mathbb{N}\odot i_{j}:\mathbb{N}}^{\mathrm{P-LABEL}}}{i_{j}:i_{j}:\mathbb{N}\odot i_{j}:\mathbb{N}}\text{P-EXT}\quad\overline{i_{k}:\mathbb{N}\odot i_{k}:\mathbb{N}}^{\mathrm{P-LABEL}}}{\frac{i_{j},i_{k}:i_{j}:\mathbb{N},i_{k}:\mathbb{N}\odot i_{j}:\mathbb{N},i_{k}:\mathbb{N}}{\left\{i_{j},i_{k}\right\}:\left\{i_{j}:\mathbb{N},i_{k}:\mathbb{N}\right\}\odot i_{j}:\mathbb{N},i_{k}:\mathbb{N}}}\text{P-EXT}}Finally, rule T-LET combines the two derivations, typing the body under the environment extended with the parameter names:
Concatenation with duplicate labels. Consider the following concatenation of two records that share the label i:
The concatenation judgement assumes that the entries of its operands line up. Subtyping therefore first adds an optional entry to the type of the left operand through S-EMPTY:
\boxed{\mathbf{L}}=\frac{\frac{\frac{\left\lfloor i?\left\{\right\}\right\rfloor^{?}}{\varepsilon\leqslant i?\left\{\right\}}\text{S-EMPTY}}{\varepsilon;\varepsilon\vdash\left\{i=3\right\}:\left\{i\triangleright\mathbb{N}\right\}}\text{T-RECORD}\quad\frac{\frac{i\triangleright\mathbb{N}\leqslant i\triangleright\mathbb{N},i?\left\{\right\}}{\left\{i\triangleright\mathbb{N}\right\}\leqslant\left\{i\triangleright\mathbb{N},i?\left\{\right\}\right\}}\text{S-EXT}}{\varepsilon;\varepsilon\vdash\left\{i=3\right\}:\left\{i\triangleright\mathbb{N},i?\left\{\right\}\right\}}\text{T-SUB}Concatenation then preserves the strong entry of the left operand, while the entry of the right operand overwrites the optional one:
\boxed{\mathbf{C}}=\frac{\frac{\overline{\varepsilon\oplus\varepsilon\mapsto\varepsilon}^{\mathrm{C-EMPTY}}}{\overline{i\triangleright\mathbb{N}\oplus\varepsilon\mapsto i\triangleright\mathbb{N}}^{\mathrm{C-STRONGL}}}\quad\frac{\overline{\quad?\oplus\triangleright\mapsto\triangleright}^{\mathrm{C-LATER}}}{\quad i\triangleright\mathbb{N},i?\left\{\right\}\oplus i\triangleright\left\{\right\}\mapsto i\triangleright\mathbb{N},i\triangleright\left\{\right\}}\quad\mathrm{C-EXT}}Finally, rule T-CONCAT combines the two derivations, yielding a record with two entries labelled i:
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
C Complete Syntax and Semantics of
term
record pattern
pattern
record
required strength
value
record value
type
record type
strength
monotype
record monotype
(Typing)
(Record Typing)
(Subtyping)
(Record Subtyping)
(Strength Subtyping)
(Record Pattern Separation)
(Pattern Separation)
(Record Type App)
(Strength App)
(Record Type Concat)
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
(Strength Concat)
C-STRONGR
C-LATER
C-LEAVE
C-REPLACE
: ⊕ ▶ ↔ ▶
? ⊕ ★ ↔ ★
: ⊕ ? ↔ :
: ⊕ : ↔ :
(Uniform)
U-EMPTY
U-EXT
(Small Step)
E-LAM
E-APPL
E-APPR
E-APP
E-FORCE
E-FORCE CLOSURE
E-BOXL
E-BOXR
E-BOX
E-ENV
E-EXTL
E-EXTL?
E-EXTR
E-CONCATL
E-CONCATR
E-CONCAT
E-PROJ
E-PROJRECORD
E-MPROJ
E-MPROJRECORD
E-DIFF
E-DIFFRECORD
E-LET
E-LETV
E-REF
E-REFV
\begin{aligned}\frac{\mathrm{E-DEREF}}{o\vdash e; o_s&\longrightarrow e'; o_s'}\\\frac{o\vdash !e; o_s&\longrightarrow !e'; o_s'}{\mathrm{E-SETR}}\\\frac{o\vdash e; o_s&\longrightarrow e'; o_s'}{o\vdash v:=e; o_s&\longrightarrow v:=e'; o_s'}\end{aligned} \begin{aligned}\frac{\mathrm{E-DEREFLOC}}{o\vdash !l; o_s&\longrightarrow\{o_s\}.l; o_s}\\\frac{\mathrm{E-SETL}}{o\vdash e_0:=e_1; o_s&\longrightarrow e_0':=e_1; o_s'}\\\frac{\mathrm{E-SET}}{o\vdash l:=v; o_s&\longrightarrow\{\}; o_s++l:v}\end{aligned}(Big Step)
B-CLOSURE
B-ENV
B-EMPTY
B-EXT?
B-MPROJ
B-DIFF
(if )
(if )
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
(if )
(if )
(if )
(if )
(if )
(if )
(if )
(if )
D Syntax-Directed Typing
The full collection of syntax-directed typing rules are as follows:
(Any Instantiation)
ST-INSTANTIATE
ST-IGNORE
(Syntax-Directed Typing)
ST-NAT
ST-CLOSURE
ST-APPANYL
ST-APPANYR
ST-APPANY
ST-FORCE
ST-RECORD
ST-CONCAT
ST-PROJ
ST-MPROJ
\begin{array}{r l r}&{}&{\rho_{s};\rho_{0}\vdash_{s}e::\forall\overline{{a_{j}}}. \left\{\rho_{1},\overline{{i_{0k}\star_{0k}A_{k},\rho_{2k}}}\right\}^{k\in[:n]}}\\ &{}&{\frac{\overline{{i_{0k}\notin\rho_{2l}}}}^{l\in[:k+1]}\overline{{k\in[:n]}}}{\rho_{s};\rho_{0}\vdash_{s}e.\left\{\overline{{i_{1k}}}\right\}^{k\in[:n]}}:\left\{\overline{{i_{1k}\star_{1k}B_{k}\left[\overline{{\tau_{j}/a_{j}}}\right]}}^{k\in[:n]}\right\}}\\ &{}&{\mathrm{S T-D I F F}}\\ &{}&{\frac{\rho_{s};\rho_{0}\vdash_{s}e::\forall\overline{{a_{j}}}. \left\{\rho_{1},\overline{{i_{0k}\star_{0k}A_{k},\rho_{2k}}}\right\}^{k\in[:n]}}{\overline{{i_{0k}\notin\rho_{2l}}}}^{l\in[:k+1]}\overline{{k\in[:n]}}}{\overline{{i_{0k}\star_{0k}A_{k}}}}^{k\in[:n]}\mathrm{p e r m u t e s}\overline{{i_{1k}\star_{1k}B_{k}}}}^{k\in[:n]}}\\ &{}&{\rho_{s};\rho_{0}\vdash_{s}e\backslash\left\{\overline{{i_{1k}}}\right\}^{k\in[:n]}\left\{\rho_{1}\left[\overline{{\tau_{j}/a_{j}}}\right],\overline{{\rho_{2k}\left[\overline{{\tau_{j}/a_{j}}}\right]}}^{k\in[:n]}\right\}}\end{array}ST-LET
ST-LOC
ST-SET
ST-DEREF
(Record Syntax-Directed Typing)
ST-EXT?
Note that application is covered by four rules, ST-APP, ST-APPANYL, ST-APPANYR, and ST-APPANY. This does not compromise syntax-directedness: the rules differ only in whether the type inferred for the function and for the argument is an “any” type ( ) or not, and these shapes are mutually exclusive, so at most one rule applies to a given application. The four rules could equivalently be presented as a single ST-APP whose premise dispatches on the shapes of the two types through an auxiliary judgement, much like record type application does on entry strengths; we keep them separate to match the mechanization.
Matthew Toohey, Ara Jamalzadeh, and Ningning Xie
(Syntax-Directed Record Pattern Separation)
(Syntax-Directed Pattern Separation)
(Syntax-Directed Record Type App)
(Syntax-Directed Strength App)
(Syntax-Directed Record Type Concat)
(Syntax-Directed Strength Concat)
E Lambda Calculus Syntax and Semantics
type
term
environment
translation environment
(STLC Typing)
LT-NAT
(STLC Small-Step)
LE-LAMAPP
F Lambda Calculus Term Approximation
approximation environment
(Term Approximation)