Scoped Effects as Parameterized Algebraic Theories

. Notions of computation can be modelled by monads. Alge-braic effects offer a characterization of monads in terms of algebraic operations and equational axioms, where operations are basic programming features, such as reading or updating the state, and axioms specify observably equivalent expressions. However, many useful programming features depend on additional mechanisms such as delimited scopes or dynamically allocated resources. Such mechanisms can be supported via extensions to algebraic effects including scoped effects and parameterized algebraic theories . We present a fresh perspective on scoped effects by translation into a variation of parameterized algebraic theories. The translation enables a new approach to equational reasoning for scoped effects and gives rise to an alternative characterization of monads in terms of generators and equations involving both scoped and algebraic operations. We demonstrate the power of our fresh perspective by way of equational characterizations of several known models of scoped effects.


INTRODUCTION
The central idea of algebraic effects [28] is that impure computation can be built and reasoned about equationally, using an algebraic theory.Effect handlers [32] are a way of implementing algebraic effects and provide a method for modularly programming with different effects.More formally, an effect handler gives a model for an algebraic theory.In this paper we develop equational reasoning for a notion arising from an extension of handlers, called scoped effects, using the framework of parameterized algebraic theories.
The central idea of scoped effects (Sec.2.2) is that certain parts of an impure computation should be dealt with one way, and other parts another way, inspired by scopes in exception handling.Compared to algebraic effects, the crucial difference is that the scope on which a scoped effect acts is delimited.This difference leads to a complex relationship with monadic sequencing (> > =).The theory and practice of scoped effects [5,25,[43][44][45][46] has primarily been studied by extending effect handlers to deal with not just algebraic operations, but also more complex scoped operations.They form the basis of the fused-effects and polysemy libraries for Haskell.Aside from exception handling, other applications include back-tracking in parsing [44] and timing analysis in telemetry [42].
Parameterized algebraic theories (Sec.2.3) extend plain algebraic theories with variable binding operations for an abstract type of parameters.They have been used to study various resources including logic variables in logic programming [37], channels in the -calculus [38], code pointers [10], qubits in quantum programming [40], and urns in probabilistic programming [41].
Contributions.We propose an equational perspective for scoped effects where scopes are resources, by analogy with other resources like file handles.We develop this perspective using the framework of parameterized algebraic theories, which provides an algebraic account of effects with resources and instances.We realize scoped effects by encoding the scopes as resources with open/close operations, analogous to opening/closing files.This paper provides: • the first syntactic sound and complete equational reasoning system for scoped effects, based on the equational reasoning for parameterized algebraic theories (Prop.4.3, Prop.4.6); • a canonical notion of semantic model for scoped effects supporting three key examples from the literature: nondeterminism with semi-determinism (Thm.4.12), catching exceptions (Thm.4.13), local state (Thm.4.14), and nondeterminism with cut (Thm.4.16); and • a reconstruction of the previous categorical analysis of scoped effects via parameterized algebraic theories: the constructors (⊳, ⊲) are shown to be not ad hoc, but rather the crucial mechanism for arities/coarities in parameterized algebraic theories (Thm.4.10).Example: nondeterminism with semi-determinism.We now briefly illustrate the intuition underlying the connection between scoped effects and parameterized algebraic theories through an example.(See Examples 2.3 and 2.7 for further details.)Let us begin with two algebraic operations: or( , ), which nondeterministically chooses between continuing 1 as computation or as computation , and fail, which fails immediately.We add semi-determinism in the form of a scoped operation once( ), which chooses the first branch of the computation that does not fail.Importantly, the scope that once acts on is delimited.The left program below returns 1; the right one returns 1 or 2, as the second or is outside the scope of once.once(or(or(1, 2), or (3,4))) once(or(1, 3)) > > = .or( , + 1) Now consider a slightly more involved example, which also returns 1 or 2: once(or(fail, or(1, 3))) > > = .or( , + 1) depicted as a tree in Fig. 1 where the red box delimits the scope of once.We give an encoding of term (1) in a parameterized algebraic theory as follows: once( .or(fail,or(close( , or(1, 2)), close( , or(3, 4))))) (2) where is the name of the scope opened by once and closed by the special close operation.By equational reasoning for scoped effects ( §3) and the equations for nondeterminism (Fig. 2), we can prove that the term (2) is equivalent to or (1,2).
Changes from the conference version.This paper is an extended version of a "fresh perspective" short paper published at ESOP 2024 [17].The additions include the following: • the scoped effect of explicit nondeterminism with cut treated as a parameterized theory (Example 3.9) and its free model (Section 4.3.4);• a discussion about how monads support operations (Defs.2.11 and 2.12), leading to a comparison between models of algebraic theories and models of parameterized theories in Props.4.8 and 4.9; • a new section about constructing a parameterized theory from an arbitrary scoped operation (Section 4.4) and how their models are related (Theorem 4.17); • proofs for the general theorems about models from Section 4.2, as well as proofs of freeness for the examples of models from Section 4.3.The proofs of freeness involve exhibiting normal forms for each parameterized theory; • an expanded discussion of existing work about the higher-order syntax approach to scoped effects, in Section 2.2; • the observation that one of the equations in the parameterized theory on nondeterminism with once is actually derivable from the others (Example 3.5); • more details about the alternative definition of catching exceptions as a parameterized theory (Remark 3.7); and • a discussion of future research about combinations of scoped theories in Section 5.

BACKGROUND 2.1 Algebraic Effects
Moggi [22,23] shows that many non-pure features of programming languages, typically referred to as computational effects, can be modelled uniformly as monads, but the question ishow do we construct a monad for an effect, or putting it differently, where do the monads modelling effects come from?A classical result in category theory is that finitary monads over the category of sets are equivalent to algebraic theories [16,18]: an algebraic theory gives rise to a finitary monad by the free-algebra construction, and conversely every finitary monad is presented by a certain algebraic theory.Motivated by this correspondence, Plotkin and Power [29] show that many monads that are used for modelling computational effects can be presented by algebraic theories of some basic effectful operations and some computationally natural equations.This observation led them to the following influential perspective on computational effects [29], which is nowadays commonly referred to as algebraic effects.

P
2.1 (P P [29]).An effect is realized by an algebraic theory of its basic operations, so it determines a monad but is not identified with the monad.
We review the framework of algebraic effects in the simplest form here and refer the reader to Plotkin and Power [31] and Bauer [2] for more discussion.Definition 2.2.A (first-order finitary) algebraic signature Σ = |Σ|, ar consists of a set |Σ|, whose elements are referred to as operations, together with a mapping ar : |Σ| → N, associating a natural number to each operation, called its arity.
Given a signature Σ = |Σ|, ar , we will write : for an operation ∈ |Σ| with ar ( ) = .The terms Tm Σ (Γ) in a context Γ, which is a finite list of variables, are inductively generated by As usual we will consider terms up to renaming of variables.Thus a context Γ = ( 1 , . . ., ) can be identified with the natural number , and Tm Σ can be thought of as a function N → Set.
The informal intuition for a term Γ ⊢ put ( ) is a program that writes the bit ∈ {0, 1} to the mutable state and then continues as another program , and a term Γ ⊢ get( 0 , 1 ) is a program that reads the state, and continues as if the state is .For example, the term , ⊢ put 0 (get( , )) first writes 0 to the state, then reads 0 from the state, so always continues as .For simplicity we consider a single bit, but multiple fixed locations and other storage are possible [29].
Definition 2.5.A (first-order finitary) algebraic theory T = Σ, is a signature Σ (Def.2.2) and a set of equations of the signature Σ, where an equation is a pair of terms Γ ⊢ and Γ ⊢ under some context Γ.We will usually write an equation as Γ ⊢ = .
Example 2.6.The theory of exception throwing has a signature containing a single operation throw : 0 and no equations.The intuition for throw is that it throws an exception and the control flow never comes back, so it is a nullary operation.
Example 2.7.The theory of explicit nondeterminism has the signature in Example 2.3 and the following equations saying that fail and or form a monoid: Following Plotkin and Pretnar [32] we refer to this as "explicit" non-determinism as it does not include full symmetry laws (that is, or( , ) = or( , )) or idempotence laws (or( , ) = ).
In this way, the monad for a computational effect is constructed in a remarkably intuitive manner, and this approach is highly composable: one can take the disjoint union of two algebraic theories to combine two effects, and possibly add more equations to characterise the interaction between the two theories [13].By contrast, coproducts of monads, which correspond to taking the disjoint union of algebraic theories, are much harder to describe explicitly even when they exist.
The kind of plain algebraic theory encapsulated by Def.2.5 above is not, however, sufficiently expressive enough for some programming language applications.In this paper we focus on two problems with plain algebraic theories: (1) Firstly, monadic bind for the monad generated by an algebraic theory is defined using simultaneous substitution of terms: given a term ∈ Tm Σ (Γ) in a context Γ and a mapping : Γ → Tm Σ (Γ ′ ) from variables in Γ to terms in some context Γ ′ , the monadic bind > > = is defined to be the simultaneous substitution [ ] of in : Monadic bind for a monad is used for interpreting sequential composition of computations.Therefore, the second clause above implies that every algebraic effect operation must commute with sequential composition.However, in practice not every effectful operation enjoys this property.(2) Secondly, it is common to have multiple instances of a computational effect that can be dynamically created.For example, it is typical in practice to have an effectful operation openFile that creates a "file descriptor" for a file at a given path, and for each file descriptor there is a pair of read and write operations that are independent of those for other files.
These two restrictions have been studied separately, and different extensions to algebraic theories generalising Def.2.5 have been proposed for each: scoped algebraic effects for the first problem above and parameterized algebraic effects for the second.At first glance, the two problems seem unrelated, but the key insight of this paper is that scoped effects can be fruitfully understood as a non-commutative linear variant of parameterized effects.

Scoped Effects
The first problem with plain algebraic theories above is that operations must commute with sequential composition.Therefore an operation ( 1 , . . ., ) is "atomic" in the sense that it may not delimit a fresh scope.Alas, in practice it is not uncommon to have operations that do delimit scopes.An example is exception catching: catch( , ℎ) is a binary operation on computations that first tries the program and if throws an exception then ℎ is run.The catch operation does not commute with sequential composition as catch( , ℎ) > > = behaves differently from catch( > > = , ℎ > > = ).The former catches only the exceptions in whereas the latter catches exceptions both in and in .Further examples include operations such as opening a file in a scope, running a program concurrently in a scope, and looping a program in a scope.
Operations delimiting scopes are treated as handlers (i.e.models) of algebraic operations by Plotkin and Pretnar [32], instead of operations in their own right.The following alternative perspective was first advocated by Wu et al. [44].P 2.10 (W .[44]).Since sequential composition of monads generated from algebraic theories is substitution, scoped operations are operations that do not commute with substitution.
Operations that do not commute with substitution arise in contexts other than computational effects as well, for example, the later modality in guarded dependent type theory [4].
We can use the results of Plotkin and Power [30] to give a precise phrasing of this on the side of semantics.For simplicity we restrict this definition to the case of monads on Set.Definition 2.11 (Plotkin and Power [30]).A monad on Set can be said to support an algebraic operation : if it is equipped with a natural transformation : ( ) → which moreover satisfies For example, any free monad determined by an algebraic theory T = Σ, according to Remark 2.9 supports all the operations in the signature Σ.As shown by Plotkin and Power [30], equation ( 7) is another phrasing of commuting with sequential composition, and indeed to give such a support for a signature Σ is to simply give a family ( ˇ ∈ ( ) | ( : ) ∈ Σ) of "generic effects", for then we can write ( ì ) = ˇ > > = ì .Hence we can make a precise definition of scoped operations by dropping (7), following Yang and Wu [46]: Definition 2.12 (Yang and Wu [46]).Let be a monad on Set.A scoped operation on the monad , of arity ∈ N, is a family of functions: : ( ) → subject only to naturality in (but not (7)).
Extensions of effect handlers to natively accommodate scoped operations were first studied by Wu et al. [44] in Haskell, where the authors proposed two approaches: (1) The bracketing approach uses a pair of algebraic operations begin and end to encode a scoped operation .For example, consider the program (put 0 ); put 1 ; , expressed in direct style, which writes the value 0 in the scope , then writes the value 1 outside of that scope and continues with the rest of the program .This can be encoded formally as: begin (put 0 (end (put 1 ( )))).
(2) The higher-order syntax approach directly constructs the syntax for programs with algebraic and scoped operations as an initial algebra of an endofunctor over the category of (finitary) endofunctors over Set.Elementarily, this amounts to adding the following rule, for every scoped operation that delimits scopes, to the rules in eq. ( 3) generating terms: The intuition is that ( 1 , . . ., ){ 1 , . . ., } is the term applying the scoped operation to the terms 1 , . . ., followed by a formal substitution that replaces the variables in with the terms 1 , . . ., respectively (c.f.explicit substitution [11] and delayed substitution [4]).Since substitutions get stuck at scoped operations, they need to be kept in terms, if we want to have a monad of terms with scoped operations.Moreover, to model the intuition that the number of internal variables after a "substitution" should not be visible in the result of "substitution" ( 1 , . . ., ){ 1 , . . ., }, the terms are further quotiented by (the congruence relation generated by) the following rule: for all , ′ ∈ N and functions : {1 . . .} → {1 . . .′ }, where the terms 1 . . .′ ⊢ [ ] are obtained by replacing each variable in with ( ) , for 1 ≤ ≤ .This rule can be motivated as follows: in the left-hand side, every variable in each is formally replaced by ( ) according to the formal substitution, while in the right-hand side, is first replaced by ( ) by the true substitution [ ], and then formally replaced by ( ) according to the formal substitution.These two results should be exactly the same since we would like our formal substitution to behave like true substitutions.
Terms in a context Γ obtained in this way also form a monad [45].The higher-order syntax approach was regarded the more principled one since in the first approach ill bracketed pairs of begin and end are possible, such as end (put 0 (begin (begin (put 1 ( ))))).
In subsequent work, both of these two approaches received further development [25,43,45,46] and operational semantics for scoped effects has also been developed [5].Of particular relevance to the current paper is the work of Piróg et al. [25], which we briefly review in the rest of this section.
Related work on models for scoped effects.Piróg et al. [25] fix the ill-bracketing problem in the bracketing approach by considering the category Set N whose objects are sequences = ( (0), (1), . ..) of sets and morphisms are just sequences of functions.Given ∈ Set N , the idea is that ( ) represents a set of terms at bracketing level for every ∈ N.
On this category, there are two functors (⊲), (⊳) : Set N → Set N , pronounced "later" and "earlier", that shift the bracketing levels: These two functors are closely related to the bracketing approach (1): a morphism : ⊳ → for a functor opens a scope, turning a term at level + 1 to the term begin( ) at level .Conversely, a morphism : ⊲ → closes a scope, turning a term outside the scope, so at level − 1, to the term end( ) at level .Given two signatures Σ and Σ ′ as in Def.2.2 for algebraic and scoped operations respectively, let Σ, Σ′ : Set N → Set N be the functors given by and conversely for every ∈ Set N , let ⇂ ∈ Set be given by ⇂ = (0).These are actually adjoint functors ↾ ⊣ ⇂.Now Prop.2.13 constructs the syntactic monad for programs with the given algebraic and scoped operations, without taking into account any equations.P 2.13 (P .[25]).The following functor can be extended to a monad that is isomorphic to the monad obtained by the higher-order syntax approach (2): where (−) * is the free monad over an endofunctor.
Piróg et al. [25] defines a model of a scoped effect as an algebra for the monad Σ + Σ′ • ⊳ + ⊲ * on Set N .This is a notion of handler accommodating both algebraic and scoped effects.In Theorem 4.10 we show that this monad on Set N arises as a special case of the free monad for a parameterized algebraic theory.In Thms.4.12-4.14,we show that three examples of models of Piróg et al. [25] are actually free algebras on ↾ ∈ Set N for an appropriate set of equations for each example.

Parameterized Algebraic Theories
Recall that our second problem with plain algebraic theories is that they do not support the dynamic creation of multiple instances of computational effects.This problem, sometimes known as the local computational effects problem, was first systematically studied by Power [35] in a purely categorical setting.A syntactic framework extending that of algebraic theories, called parameterized algebraic theories, was introduced by Staton [37,38] and is used to give an axiomatic account of local computational effects such as restriction [27], local state [29], and the -calculus [21,36].
Operations in a parameterized theory are more general than those in an algebraic theory because they may use and create values in an abstract type of parameters.The parameter type has different intended meanings for different examples of parameterized theories, typically as some kind of resource such as memory locations or communication channels.In this paper, we propose to interpret parameters as names of scopes.P 2.14.Scoped operations can be understood as operations allocating and consuming instances of a resource: the names of scopes.
In the case of local state, the operations of Example 2.4 become get( , 0 , 1 ) and put ( , ), now taking a parameter which is the location being read or written to.In a sense, each memory location represents an instance of the state effect, with its own get and put operations.We also have a term new ( .( )) which allocates a fresh location named storing an initial value , then continues as ; the computation might mention location .The following is a possible equation, which says that reading immediately after allocating is redundant: For the full axiomatization of local state see [38, §V.E].A closed term can only mention locations introduced by new , meaning that type of locations is abstract.
To model scoped operations, we think of them as allocating a new scope.For example, the scoped operation once, which chooses the first non-failing branch of a nondeterministic computation, is written as once( .( )).It creates a new scope and proceeds as .As in §1, there is an explicit operation close( , ) for closing the scope and continuing as .
Well-formed programs close scopes precisely once and in the reverse order to their allocation.Thus in §3 we will discuss a non-commutative linear variation of parameterized algebraic theories needed to model scoped effects.With our framework we then give axiomatizations for examples from the scoped effects literature (Thms.4.12-4.14).
Our parameters are linear in the same sense as variables in linear logic and linear lambda calculi [3,12], but with an additional non-commutativity restriction.Non-commutative linear systems are also known as ordered linear systems [24,33].A commutative linear version of parameterized algebraic theories was considered by Staton [40] to give an algebraic theory of quantum computation; in this case, parameters stand for qubits.
Remark 2.15.Parameterized algebraic theories characterize a certain class of enriched monads [37], extending the correspondence between algebraic theories and monads on the category of sets, and the idea of Plotkin and Power [29] that computational effects give rise to monads (see §2.1).Thus, the syntactic framework of parameterized theories has a canonical semantic status.We can use the monad arising from a parameterized theory to give semantics to a programming language containing the effects in question.
The framework of parameterized algebraic theories is related to graded theories [14], which also use presheaf-enrichment; second-order algebra [7][8][9], which also use variable binding; and graphical methods [19], which also connect to presheaf categories.

PARAMETERIZED THEORIES OF SCOPED EFFECTS
In order to describe scoped effects we use a substructural version of parameterized algebraic theories [37].A theory consists of a signature (Def.3.1) and equations (Def.3.4) between terms formed from the signature.Terms contain two kinds of variables: computation variables ( , , . . .), which each expect a certain number of parameters, and parameter variables ( , , . . .).In the case of scoped effects, a parameter represents the name of a scope.
Any scoped signature gives rise to a parameterized algebraic signature (Section 3.1).But a parameterized algebraic theory includes equations as well as operations.In Section 3.2 we propose equational theories for various scoped effects: exceptions, state, and non-determinism.In Section 4.3 we show that the free models of these theories completely capture these notions from the literature.For a given signature, we define the terms-in-context of algebra with non-commutative linear parameters.A context Γ of computation variables is a finite list 1 : 1 , . . ., : , where each variable is annotated with the number of parameters it consumes.A context Δ of parameter variables is a finite list 1 , . . ., .Terms Γ | Δ ⊢ are inductively generated as follows: In the conclusion of the last rule, the parameters 1 ... are consumed by the operation O.The parameters 1 ... are bound in .As usual, we treat all terms up to renaming of variables.When = = 0, i.e.O is a constant symbol, we omit the parentheses.The context Γ of computation variables admits the usual structural rules: weakening, contraction, and exchange; the context Δ of parameters does not.All parameters in Δ must be used exactly once, in the reverse of the order in which they appear.Intuitively, a parameter in Δ is the name of an open scope, so the restrictions on Δ mean that scopes must be closed in the opposite order that they were opened, that is, scopes are well-bracketed.The arguments 1 , ... , of an operation O are continuations, each corresponding to a different branch of the computation, hence they share the parameter context Δ.
Compared to the algebra with linear parameters used for describing quantum computation [40], our syntactic framework has the additional constraint that Δ cannot be reordered.Given these constraints, the context Δ is in fact a stack, so inside a term it is unnecessary to refer to the variables in Δ by name.We have chosen to do so anyway in order to make more clear the connection to non-linear parameterized theories [37,38].
The syntax admits the following simultaneous substitution rule: In the conclusion, the notation (Δ ′ , 1 ... ⊢ )/ emphasizes that the parameters ( 1 . . . ) in are replaced by the corresponding parameters that consumes in , either bound parameters or free parameters from Δ.To ensure that the term in the conclusion is well-formed, we must substitute a term that depends on Δ ′ for all the computation variables in the context of .
An important special case of the substitution rule is where we add a number of extra parameter variables to the beginning of the parameter context, increasing the sort of each computation variable by the same number.The following example instance of (18), where ar (O) = (1 | 1), illustrates such a "weakening" by adding two extra parameter variables ′ 1 , ′ 2 and replacing : 2 by ′ : 4. We will omit the qualifier "with non-commutative linear parameters" where convenient and refer to "parameterized theories" or just "theories".
Given a theory T = Σ, , we form a system of equivalence relations = T,(Γ|Δ) on terms in each context (Γ | Δ), by closing substitution instances of the equations in under reflexivity, symmetry, transitivity, and congruence rules: Examples of equations, i.e. pairs of terms in the same context, are given in Figure 2. As an illustration, we note that Equation ( 14) is derivable from the others: Example 3.6.As we mentioned earlier, exception catching is not an ordinary algebraic operation.The signature for throwing and catching exceptions is the following: The throw operation uses no parameters and takes no continuations.The catch operation uses no parameters and takes two continuations which each open a new scope, by binding a fresh parameter.Exceptions are caught in the first continuation, and are handled using the second continuation.
The close operation uses one parameter and takes one continuation binding no parameters.The term close( , ) closes the scope named by and continues as .For example, in the term catch( .close(, ), .( )), exceptions in will not be caught, because the scope of the catch operation has already been closed.The equations are: :0, : This seems more natural as there is no need to delimit a scope in the second continuation, which handles the exceptions.We could also encode varcatch in the theory of catch by making the following definition: and deducing the two equations for varcatch from eqs. ( 19) and (21).
Example 3.8 (Mutable state with local values).The theory of (boolean) mutable state with one memory location (Ex.2.4) can be extended with scoped operations local 0 and local 1 that write respectively 0 and 1 to the state.Inside the scope of local, the value of the state just before the local is not accessible anymore, but when the local is closed the state reverts to this previous value.
The equations for the parameterized theory of state with local comprise the usual equations for state in the literature [20,29]: together with equations for local/close, and the interaction with state: This extension of mutable state is different from the one discussed in §2.3, where memory locations can be dynamically created.
Example 3.9 (Explicit nondeterminism with cut).The theory of explicit nondeterminism given by eqs.( 9) to (11) can be extended with an operation that prunes the list of possible results, similar to cut in Prolog: The cut operation is algebraic and has one continuation; cut( ) intuitively discards the choices that have not been explored yet, and returns all the possible results of .The behaviour of cut has been axiomatized in [26,Sec. 6]: : 0, : To delimit the scope in which cut discards choices, we add an operation that opens a scope, and a close operation for closing scopes: We propose the following equations for scope: : 0, : 1 | − ⊢ scope( .or(close(, ), ( ))) = or( , scope( .( ))) Intuitively, eq. ( 33) says that when a cut reaches the boundary of a scope, the cut is erased so it cannot affect choices outside of the scope.The Haskell implementation of the scope function by Piróg and Staton [26] has similar behaviour.
Equation (34) axiomatizes the interaction between opening and closing a scope.From it, we can derive the following: Remark 3.10.We can almost encode the theory of once from Example 3.5 into the theory for cut and scope (Example 3.9), by defining once to be scope, and defining the close( , ) of the once theory to be cut(close( , )).Then we can recover eqs.( 12), ( 14) and ( 15) from Figure 2, by using eqs.( 29) to (34); but we cannot recover eq. ( 13), which is idempotence of or inside a once.

MODELS OF PARAMETERIZED THEORIES 4.1 Models in Set N
Models of first-order algebraic theories [2] consist simply of a set together with specified interpretations of the operations of the signature, validating a (possibly empty) equational specification.The more complex arities and judgement forms of a parameterized theory require a correspondingly more complex notion of model.Rather than simply being a set of abstract computations, a model will now be stratified into a sequence of sets = ( (0), (1), . ..) ∈ Set N where ( ) represents computations taking parameters.In §2.2 we described Piróg et al's somewhat different use of Set N [25].We connect the two approaches in Thm.4.10 below.

P
. By induction on the structure of derivations.
Remark 4.4.A more abstract view on models is based on enriched categories, since parameterized algebraic theories can be understood in terms of enriched Lawvere theories [15,34,37].This is useful because, by interpreting algebraic theories in different categories, we can combine the algebra structure with other structure, such as topological or order structure for recursion [1, §6], or make connections with syntactic categories [39].Recall that the category Set N has a 'Day convolution' monoidal structure [6]: ( ⊗ ) ( ) =

Free Models and Monads
Strong monads are of fundamental importance to computational effects [23].Algebraic theories give rise to strong monads via free models.
In slightly more detail, there is an evident notion of homomorphism applicable to Σ-structures and T -models, and thus we can sensibly discuss Σ-structures and T -models that are free over some collection ∈ Set N of generators.(2) T extends to a monad on Set N , strong for the Day tensor.
(3) The derivable equality (= T ) in a parameterized algebraic theory T is complete: if an equation is valid in every T -model, then it is derivable in = T .
A monad on Set N strong for the Day tensor is a monad in the usual sense equipped with a strength ⊗ → ( ⊗ ), where ⊗ is the Day tensor defined in Rem.4.4.

P .
The first part of ( 1) is straightforward and standard: the interpretation of operation symbols is read off from (17).For the second part, we use the variable introduction rule (16) 3) follows since all terms are interpreted in free models "as themselves", and two terms are derivably equal iff their denotations in the free model are equal.
For (2), the just defined becomes the monadic unit, and bind is defined in terms of substitution as usual (rule ( 18)).By the general properties of the Day tensor product, the strength is determined by a natural transformation
In Section 4.3 we will consider explicit syntax-free characterizations of the free models for particular scoped theories.For completeness, we mention that T is part of an equivalence between such sifted-colimit-preserving strong monads and parameterized theories, e.g.[40, §5].We omit details as this will not be used in the rest of this paper.P 4.7.The functor T preserves colimits.Moreover, there is an equivalence between parameterized algebraic theories and monads on Set N strong for the Day tensor and whose functor part preserves sifted colimits.
Relating parameterized theories and algebraic theories.In Prop.4.8 and theorem 4.10 we relate the free model construction T to monads on Set that support algebraic and scoped operations, as discussed in Section 2.2.We also discuss an encoding of algebraic theories as parameterized theories (Prop.4.9), which will be extended to include scoped operations in Section 4.4.
Recall from Section 2.2 that the functors ↾ : Set → Set N and ⇂ : Set N → Set form an adjunction.The monad T induces a monad on Set: P 4.8.Let T = Σ, be a parameterized algebraic theory arising from signatures for algebraic and scoped operations (Remark 3.2).
(1) For each algebraic operation ( : ), the monad ′ T supports an algebraic operation of the same arity, in the sense of Def.2.11.
(2) For every scoped operation ( : ), the monad ′ T supports a scoped operation of the same arity, in the sense of Def.2.12.

P
. We have a natural transformation ( T ) → T given by substituting terms into the operation and this is "algebraic" in the sense of commuting with postcomposition by the monadic multiplication, so (1) follows easily.In general, an operation : (0 | 1, ... , 1) appears as a natural transformation (⊳ T ) → T .However, it is easy to show that ⊳ preserves T -models, and in the setting of (2) we have can use close : By the universal property of free models, this induces another map T → ⊳ T .This map adds a close at the leaves of each syntax tree, as opposed to at the root.Postcomposing T → ⊳ T with the scoped operation (⊳ T ) → T , we have a natural transformation ( T ) → T which restricts to the desired scoped operation on ′ T .Prop. 4.8 ( 1) is still true when applied to operations with arity (0 | 0, ... , 0) part of an arbitrary parameterized signature.
Key to Perspective 2.1 is that an algebraic theory determines a monad on Set.An ordinary algebraic theory T can be considered as a parameterized algebraic theory in at least two ways.Let T 1 be the "minimal translation": the parameterized theory whose signature consists only of operations of arity (0 | 0, ... , 0) plus all equations; and let T 2 be T 1 together with an operation close : (1 | 0).Thus T 2 arises when translating into a parameterized theory via a scoped signature as in Remark 3.2, albeit with no scope-opening operations.P 4.9.Let T = Σ, be an algebraic theory and inducing a monad on Set.Then is isomorphic to the Set restriction of the monads induced by the parameterized theories T 1 and T 2 (defined in eq. ( 35)), respectively:

P
. We will prove something stronger.It is easy to see that for any ∈ Set N , ( T 1 ) ( ) ( ( )), since a T 1 -algebra structure on ∈ Set N is equivalent to a T -algebra structure on each ( ) with no compatibility requirements.Then by definition of the functors ↾and ⇂ we obtain that ′ T 1 ( ) ( ) for any set .For T 2 , we can at least characterize T 2 (↾ ), for a set .It is given by ¯ ≔ .+1 , with the obvious interpretation of the algebraic operations in Σ, and close ¯ , : +1 → +2 given by the monadic unit +1 .To see that ¯ is the free model of T 2 , given any T 2 -model with a map ↾ → , we define a map ¯ → as follows.Since each ( ) is, in particular, a -algebra, we get a unique -homomorphism → (0).Now we can inductively construct -homomorphisms +2 → ( + 1): composing +1 → ( ) constructed so far with close , : ( ) → ( + 1), and extending uniquely to a -homomorphism +2 → ( + 1).The resulting map ¯ → a T 2 -homomorphism since it commutes with the interpretations of close by construction.This establishes the connection with monads for ordinary algebraic theories.Finally, we will connect T with the scoped monad of Prop.2.13 that was first given by Piróg et al. [25].

Free Models for Scoped Effects
We now turn to some concrete models from Piróg et al. [25].To characterize them as certain free models of parameterized algebraic theories, we need the following notion.
Equivalently, is truncated if = ↾ ( (0)).The free model on a truncated corresponds to the case where computation variables can only denote programs with no open scopes.This is the case in the development of Piróg et al. [25], where if the programmer opens a scope, a matching closing of the scope is implicitly part of the program.

Nondeterminism with once.
Recall the parameterized theory for nondeterminism with once (signature in Ex. 3.3 and equations in Fig. 2).It follows from Prop.4.6 that this theory has a free model on each in Set N , with carrier denoted by o ( ) ∈ Set N .For truncated, the free model on has an elegant description: Here List( ) is the set of lists over .(So List +1 ( (0)) can be thought of as the set of balanced trees of depth exactly + 1 but with arbitrary degree, and leaves labelled by (0), where we distinguish between nodes with zero degree and leaf nodes.) In this case the interpretation of once chooses the first element of a list and closing a scope wraps its continuation as a singleton list.Choice is interpreted as list concatenation (+ +), and failure as the empty list []: In fact the model o ( ) we just described is the same as the model for nondeterminism of Piróg et al. [25,Example 4.2]: T 4.12.For a truncated ∈ Set N , o ( ) is the free model of the parameterized theory of nondeterminism with once (Example 3.5 and Figure 2).Moreover, the model for nondeterminism with once from [25, Example 4.2], starting from a set , is the free model on ↾ ∈ Set N .

P
. It is easy to show that the operations on o ( ) defined in this section satisfy the equations in Figure 2, and therefore o ( ) is a model.Denote by o ( ) the free model in the sense of Prop.4.6.We apply the definition of freeness to the map → o ( ) that sends each ∈ (0) to the singleton list [ ], to obtain a homomorphism of models : o ( ) → o ( ).To show o ( ) is free, we show that has an inverse : o ( ) → o ( ).
Recall that o ( ) ( ) contains equivalence classes of terms in context, with computation variables taken from .We use representatives of these equivalence classes where the context Γ contains a variable ( : 0) for each element of (0).We define by induction: The terms in the image of are essentially normal forms for the parameterized theory, when computation variables only have arity 0.
We show that is a homomorphism of models, meaning it commutes with the operations in the theory, using the equations in Figure 2. The case for once also requires an induction on lists.
To show • = id o ( ) , we use induction on ∈ N, followed by induction on lists, and the fact that is a homomorphism.To show • = id o ( ) , we do induction on the term formation rules, and use the fact that is a homomorphism.

Exceptions.
Recall the parameterized theory of throwing and catching exceptions in Ex. 3.6 and (19-21).For truncated ∈ Set N , the free model of the theory of exceptions has carrier: c ( ) ( ) = (0) + { 0 , . . ., } where − corresponds to the term (in normal form) that closes scopes then throws.
To define the operations catch and close we pattern match on the elements of c ( ) ( + 1) using the isomorphism c ( ) ( + 1) c ( ) ( ) + { +1 }.Below, is an element of c ( ) ( ), standing for a computation in normal form: The cases in the definition of catch correspond to equations ( 21), ( 19), ( 20) respectively.In the third case, an exception inside + 1 scopes in the second argument of catch becomes an exception inside scopes.T 4.13.For a truncated ∈ Set N , c ( ) is the free model for the parameterized theory of exceptions (19)(20)(21).The model for exception catching from [25,Example 4.5], which starts from a set , is the free model on ↾ ∈ Set N .

P
. We follow the same outline as for the proof of Theorem 4.12.Consider the map → c ( ) that maps each element of (0) to itself.This has a unique extension to a map out of the free model on , : c ( ) → c ( ).We define : c ( ) → c ( ) to be the candidate inverse for .Note that it is enough to show that is an inverse in Set N .Using the intuition of normal forms and the isomorphism c ( ) ( ) (0) + { 0 , . . ., }: To show • = id c ( ) we use that is a homomorphism.For • = id c ( ) , we proceed by induction on the term formation rules.We use eq.(36), and in the catch case we also use the eqs.(19) to (21) from the parameterized theory.
get : l ( ) ( ) 2 → l ( ) ( ) get ( , ) = .= 0 otherwise Notice that the continuation of local uses the new state , whereas close discards the state which comes from the scope that is being closed.

P
. We show that l ( ) is the free model following the same proof outline for Theorems 4.12 and 4.13.It is easy to equip ′ l ( ) with operations and do a similar proof of freeness.Consider the map → l ( ) that sends each ∈ (0) to the function .( , ), and let : l ( ) → l ( ) be its unique extension out of the free model.We define a candidate inverse for using the intuition of normal forms, : l ( ) → l ( ):

))
where we identified the elements of (0) with the variables in Γ .
We can show that is a homomorphism using eqs.( 22) to ( 28) from the parameterized theory.To show • = id l ( ) , we proceed by induction on ∈ N and use the fact that is a homomorphism.For • = id l ( ) , we use induction on terms and that both and are homomorphisms.For the variable case, we use eq.( 22).
The interpretations in l ( ) and ′ l ( ), i.e that of Piróg et al. [25], of programs with no open scopes agree: l ( ) and is defined as
The fundamental property for this logical relation says that for all terms Γ | 1 , ... , ⊢ , the two interpretations are related: l ( ),0 , ′ l ( ),0 ∈ R .If = 0, this is enough to deduce the interpretations are equal.The fundamental property is proved by induction on .
The restriction of Γ in Prop.4.15 to computation variables that do not depend on parameters and of Δ to be empty are reasonable because in the framework of Piróg et al. [25], only programs with no open scopes are well-formed.Therefore, only such programs can be substituted in , justifying the restriction of  Define a functor on sets Idem: Here in the notation * , the * is just a flag.It is a semantic counterpart of cut, meaning 'discard the yet uninspected choices and continue with ', following [26, §6].(It is not the Kleene star of Prop.2.13.)If is truncated, the carrier of the free model on is: ). (So these can be thought of as balanced binary trees, depth +1, leaves labelled by (0), and where each non-leaf node is optionally flagged with * .) When writing the interpretation of operations, we use the isomorphism cs ( ) (0) Idem(List( (0)))) cs ( ) ( + 1) Idem(List( cs ( ) ( ))) so an element of cs ( ) ( ) is either a list xs or a starred list xs * .
The interpretation of cut and or in the free model is the following: The cut operation marks a list with a star; the second clause in the definition of cut corresponds to the idempotence equation (31).Similarly to Section 4.3.1, or performs list concatenation, but now stars need to be taken into account as well.The second clause in definition of or corresponds to eq. ( 30), and the third clause to eq. ( 29).
The operation of opening a scope is interpreted as: The first clause corresponds to erasing cuts as in eq. ( 33).The second clause corresponds to eq. ( 32).The third clause uses the interpretation of or to concatenate lists while taking into account cuts; it corresponds to eq. ( 34).The close and fail operations have the same interpretation as in the nondeterminism with once example from Section 4.3.1: ) is the free model of the parameterized theory of nondeterminism with cut, defined in Example 3.9.

P
. We explained in this subsection why cs ( ) together with its interpretation of operations respects the equations of the parameterized theory.Therefore, cs ( ) is a model of the theory, in the sense of Def.4.2.
Denote by cs ( ) the free model on for nondeterminism with cut, in the sense of Prop.4.6.Consider the map → cs ( ) that sends each element of (0) to the singleton list containing that element.By freeness (Def.4.5), this map has a unique extension to a homomorphism of models : cs ( ) → cs ( ).To show cs ( ) is free, it is enough to show that has an inverse.Recall that cs ( ) ( ) is isomorphic to (Idem • List) +1 ( (0)), and cs ( ) ( ) contains equivalence classes of terms in context, where the computation variables come from .We define a candidate inverse : cs ( ) → cs ( ) by induction on ∈ N and on lists.For simplicity, we use representatives of equivalence classes from cs ( ) ( ) where the context Γ contains one variable : 0 for each ∈ (0), so we identify and in the definition below: The terms in the image of can be seen as the normal forms for the parameterized theory, defined recursively.
To show that is a section, • = id cs ( ) , we use induction on ∈ N.For both the base case and the induction step, we first consider the case where the input is a list xs and use induction on lists.We use this intermediate result to prove the case of a starred list xs * .Throughout, we use the fact that is a homomorphism.
To show • = id cs , we fist show is a homomorphism of models, i.e that it commutes with all the operations.The or and scope cases require induction on lists.Most importantly, we make use of equations from the parameterized theory of cut (Example 3.9).We then show by induction on the term formation rules that: where the equality = cs is in the theory of cut.We use the equations in the theory and the fact that is a homomorphism.The scope case also requires an induction on lists.

Generating a Parameterized Theory from an Arbitrary Scoped Operation
In Remark 3.2 we showed how to translate signatures of arbitrary algebraic and scoped (Def.2.2 and section 2.2) operations into parameterized signatures.We then showed in Section 3.2 how to encode the behaviour of several examples of scoped operations using equations that form parameterized theories.In Section 4.3, we constructed free models for these examples of scoped operations.
In this section, we show how to obtain a parameterized theory from an arbitrary scoped operation, and discuss the free model of such a theory.Recall from Perspective 2.10 that a scoped operation is one that does not commute with substitution, and more precisely from Def. 2.12 that a scoped operation on a monad on Set is a natural transformation : ( ) → .Starting from an algebraic theory T = Σ, , with monad supporting a scoped operation with arity , we can construct a parameterized theory T param in the sense of Def.4.17.Let T = Σ, be an algebraic theory inducing a monad on Set, supporting a scoped operation of arity .With T param constructed as above, we have the following isomorphism: Moreover, the scoped operation on ′ T param corresponding to sc, as constructed in Prop.4.8, agrees with the operation .

P
. In fact, we will show that the free model T param on a truncated object ↾ , for a set , is ¯ ≔ .+1 , from the proof of Prop.4.9.We first note that ¯ supports an interpretation of sc by the follow morphism: To check that ¯ is a model of T param , we need to see that all instances of (37) are validated.Note that, for terms 1 : 0, .. Since ¯ is free on ↾ for the theory T 2 of Prop.4.9, which omits sc and the equations (37), we only need to show that a T 2 -homomorphism ¯ → into a T param -model is always a T param -homomorphism, i.e. that it commutes with sc.But every element of ¯ ( + 1) = ( ¯ ( )) is in the image of +1 • close for some Σ-term 1 , ... , ⊢ , thus this amounts to the hypothesis that validates all instances of eq. ( 37).
Remark 4.18.Whereas in Section 3.2 we constructed scoped theories out of particular algebraic theories whose monads support a scoped operation, the recipe for T param constructs a scoped theory in the general case.However, the presentation of T param typically includes infinitely many equations whereas the theories in Section 3.2 are given finite presentations.For example, in the case of once (Figure 2), eqs.( 13) and (15) are not part of T param but infinitely many substitution instances of them are.The free models of T param and that in Section 4.3.1 agree on truncated , (since the free model of the algebraic theory of explicit nondeterminism is List), which shows that the theory of once admits derivations of all equations of the corresponding T param .However, eqs. ( 13) and (15) are not derivable in T param .We argue that the full behaviour of once is captured by the theory in Figure 2, rather than by T param .

SUMMARY AND RESEARCH DIRECTIONS
We have provided a fresh perspective on scoped effects in terms of the formalism of parameterized algebraic theories, using the idea that scopes are resources (Rem.3.2).As parameterized algebraic theories have a sound and complete algebraic theory (Props.4.3, 4.6), this carries over to a sound and complete equational theory for scoped effects.We showed that our approach recovers the earlier models for scoped non-determinism, exceptions, and state (Thms.4.12-4.14).
Here we have focused on equational theories for effects alone.But as is standard with algebraic effects, it is easy to add function types, inductive types, and so on, together with standard beta/eta theories (e.g.[30], [40, §5]).This can be shown sound by the simple models considered here, as indeed the canonical model Set N is closed and has limits and colimits.

Combinations of theories.
A more concrete research direction is to define combinations of parameterized theories, and hence of scoped effects, using sum and tensor, generalizing combinations of algebraic effects [13].Informally, the tensor corresponds to all the operations from one theory commuting with the operations from the other.But in the case of parameterized theories in Set N , defining what this means for operations to commute is delicate because substitution, eq. ( 18), is more complex than in the algebraic case (but see [38,Def. 2]).
For example, consider the commuting combination of explicit nondeterminism with once (fig.2) and global state (Example 2.8).In the resulting theory, the state is rolled back when a computation fails.For example, the fact that put 0 commutes with fail means we can prove: put 1 or(put 0 (fail), get( 0 , 1 )) = put 1 or(fail, get( 0 , 1 )) = put 1 get( 0 , 1 ) = put 1 ( 1 ) using commutativity of put 0 and fail for the first step.The fact that put and get commute with once and close means the state operations are independent of scopes.
Our work opens up new directions for scoped effects, in theory and in practice.By varying the substructural laws of parameterized algebraic theories, we can recover foundations for scoped effects where scopes (as resources) can be reordered or discarded, i.e.where they are not wellbracketed, already considered briefly in the literature [25].For example, the parameterized algebraic theory of qubits [40] might be regarded as a scoped effect, where we open a scope when a qubit is allocated and close the scope when it is discarded; this generalizes traditional scoped effects as multi-qubit operations affect multiple scopes.

3. 1
Parameterized Algebraic Theories with Non-Commutative Linear Parameters Definition 3.1.A (parameterized) signature Σ = |Σ|, ar consists of a set of operations |Σ| and for each operation O ∈ |Σ| a parameterized arity ar (O) = ( | 1 ... ) consisting of a natural number and a list of natural numbers 1 , ... , .This means that the operation O takes in parameters and continuations, and it binds parameters in the -th continuation.Remark 3.2.Given signatures for algebraic and scoped operations, as in Def.2.2 and §2.2, we can translate them to a parameterized signature as follows: • for each algebraic operation (op : ) of arity ∈ N, there is a parameterized operation with arity (0 | 0 ... 0), where the list 0 ... 0 has length ; • for each scoped operation (sc : ) of arity ∈ N, there is a parameterized operation sc : (0 | 1 ... 1), where the list 1 ... 1 has length ; • there is an operation close : (1 | 0), which closes the most recent scope, and which all the different scoped operations share.Not every parameterized signature arises from a scoped signature, because in general we may have operations where the arguments have different valences (e.g. 1 ≠ 2 ).So parameterized signatures give some more flexibility.We explore this point more in Remark 3.2.Example 3.3.The algebraic theory of explicit nondeterminism in Example 2.3 can be extended with a semi-determinism operator once: or : (0 | 0, 0) once : (0 | 1) fail : (0 | −) close : (1 | 0) (We write − for an empty list or context.)The continuation of once opens a new scope, by binding a parameter.Inside this scope, only the first successful branch of or is kept.We consider the terms and equations in Example 3.5 and Fig. 2.

)) Definition 3 . 4 .
An algebraic theory T = Σ, with non-commutative linear parameters is a parameterized signature Σ together with a set of equations.An equation is a pair of terms Γ | Δ ⊢ and Γ | Δ ⊢ in the same context (Γ | Δ).We write an equation as Γ | Δ ⊢ = .

. 2
Examples of Equations for Scoped Theories via Parameterized Presentations Example 3.5.We continue Example 3.3, semi-determinism, with or, once, fail and close.The term formation rules in Section 3.1 allow the most recently opened scope to be closed using the close operation by consuming the most recently bound parameter; close has one continuation which does not depend on any parameters.

Definition 4 . 2 .
Let T be a parameterized theory over the signature Σ.A Σ-structure X is a model of T if for every equation Γ | Δ ⊢ = in T , and every ∈ N, we have an equality of functions Γ | Δ ⊢ X, = Γ | Δ ⊢ X, .

P 4 . 3 .
The derivable equality (= T ) in a parameterized algebraic theory T is sound: every T -model satisfies every equation of = T .

Definition 4 . 5 .
Consider a T -model Y with carrier ∈ Set N and a morphism : → in Set N .Then Y is free on , if for any other model Z and any morphism : → in Set N , there exists a unique homomorphism of models ˆ : Y → Z, that extends , meaning ˆ • = in Set N .Informally, for a theory T we define T ∈ Set N by taking T ( ) to be the set of = Tequivalence classes of terms with parameter context 1 , . . ., whose -ary computation variables come from ( ).More formally, we let T ( ) = { [ 1 : 1 , . . ., : | 1 , . . .⊢ ] = T , 1 , . . ., | ∈ ( )}/∼ where the equivalence relation ∼ allows us to -rename context variables in the term judgements and apply permutation, contraction or weakening to the computation context paired with the corresponding transformation of the tuple 1 , . . ., .It is straightforward to make T into a Σstructure.P 4.6.(1) T is a T -model, and moreover a free T -model over .

T 4 . 10 .
Consider signatures for algebraic Σ and scoped Σ ′ effects with no equations, inducing a parameterized algebraic theory T (via Rem.3.2).We have an isomorphism of monads T Σ + Σ′ • ⊳ + ⊲ * .P .To see this, we use the description of T ( ) as a set of equivalence classes of Tterms with computation variables coming from .We show that T ( ) is isomorphic to the set Σ + Σ′ • ⊳ + ⊲ * ( ) ( ).Consider the outermost operation of a term in T ( ): it is either algebraic, scoped or close.Each component of the sum on the right-hand-side, Σ, Σ′ • ⊳ and ⊲ corresponds to one of these three possibilities.Scoped operations bind a parameter hence the need for the ⊳ functor which increases the index by 1.The close operation consumes a parameter which corresponds to the fact that ⊲ decreases the index by 1.Note that according to Def. 4.1, for an arbitrary carrier , the interpretation of close has type → ⊳ , which is equivalently a morphism ⊲ → .Both ⊳/⊲ are characterized in Rem.4.4 in terms of the Day tensor of Set N .

4 . 14 .
is the model of state with local proposed in [25, §7.1]: T Given a truncated ∈ Set N , l ( ) is the free model of the parameterized theory of state with local values, eqs.(22) to (28).Moreover, ′ l ( ) is the free model for eqs.(22) to (27).Consider the example of state with local variables from Piróg et al. [25, §7.1], specialized to one memory location storing one bit, reading the return type (there ' ') as a set .The model proposed in [25, §7.1] is the free model on ↾ for the parameterized theory with equations (22-27).

4. 3 . 4
Nondeterminism with cut.Recall the parameterized theory of explicit nondeterminism with cut from Example 3.9.According to Prop.4.6, this theory has a free model for each ∈ Set N , denoted by cs ( ).