Scholarly article on topic 'Monads and Adjunctions for Global Exceptions'

Monads and Adjunctions for Global Exceptions Academic research paper on "Computer and information sciences"

CC BY-NC-ND
0
0
Share paper
Keywords
{"exception handling" / monad / adjunction / comonad / coalgebra / call-by-push-value / "Beck's theorem"}

Abstract of research paper on Computer and information sciences, author of scientific article — Paul Blain Levy

Abstract In this paper, we look at two categorical accounts of computational effects (strong monad as a model of the monadic metalanguage, adjunction as a model of call-by-push-value with stacks), and we adapt them to incorporate global exceptions. In each case, we extend the calculus with a construct, due to Benton and Kennedy, that fuses exception handling with sequencing. This immediately gives us an equational theory, simply by adapting the equations for sequencing. We study the categorical semantics of the two equational theories. In the case of the monadic metalanguage, we see that a monad supporting exceptions is a coalgebra for a certain comonad. We further show, using Beck's theorem, that, on a category with equalizers, the monad constructor for exceptions gives all such monads. In the case of call-by-push-value (CBPV) with stacks, we generalize the notion of CBPV adjunction so that a stack awaiting a value can deal both with a value being returned, and with an exception being raised. We see how to obtain a model of exceptions from a CBPV adjunction, and vice versa by restricting to those stacks that are homomorphic with respect to exception raising.

Academic research paper on topic "Monads and Adjunctions for Global Exceptions"

Electronic Notes in Theoretical Computer

www.elsevier.com/locate/entcs

Monads and Adjunctions for Global Exceptions

Paul Blain Levy1

School of Computer Science University of Birmingham Birmingham B15 2TT, U.K.

Abstract

In this paper, we look at two categorical accounts of computational effects (strong monad as a model of the monadic metalanguage, adjunction as a model of call-by-push-value with stacks), and we adapt them to incorporate global exceptions. In each case, we extend the calculus with a construct, due to Benton and Kennedy, that fuses exception handling with sequencing. This immediately gives us an equational theory, simply by adapting the equations for sequencing. We study the categorical semantics of the two equational theories.

In the case of the monadic metalanguage, we see that a monad supporting exceptions is a coalgebra for a certain comonad. We further show, using Beck's theorem, that, on a category with equalizers, the monad constructor for exceptions gives all such monads.

In the case of call-by-push-value (CBPV) with stacks, we generalize the notion of CBPV adjunction so that a stack awaiting a value can deal both with a value being returned, and with an exception being raised. We see how to obtain a model of exceptions from a CBPV adjunction, and vice versa by restricting to those stacks that are homomorphic with respect to exception raising.

Keywords: exception handling, monad, adjunction, comonad, coalgebra, call-by-push-value, Beck's theorem

1 Introduction

1.1 Monads For Exceptions

In a seminal paper [19], Moggi brought together a range of imperative behaviours that have come to be called computational effects, including divergence, nondeterminism, storage and exceptions. The present paper is a study

1 Email: pbl@cs.bham.ac.uk

Available online at www.sciencedirect.com

DIRECT'

SCIENCE ^ I

Electronic Notes in Theoretical Computer Science 158 (2006) 261—

1571-0661/$ - see front matter © 2006 Published by Elsevier B.V. doi:10.1016/j.entcs.2006.04.014

of the last example. For the sake of precision, let us distinguish some variations on the effect of exceptions.

• Some languages, such as Java, distinguish between errors and exceptions. The former cannot be caught: when an error is raised, execution immediately terminates. By contrast, exceptions can be caught (aka handled).

• Some languages, such as ML, allow the dynamic generation of new exception names, and this is modelled using games in [8]. But in the present paper, we look at global exceptions only.

In the study of effects, various calculi have been studied, including computational A-calculus [18], monadic metalanguage [19], fine-grain call-by-value [12], call-by-push-value (CBPV) [11], CBPV with stacks [14]. And various categorical structures have been studied as models of these calculi, including strong monads [19], Freyd categories [16], ^-categories [16], CBPV adjunctions [14].

None of the above calculi contain constructs for specific effects; such constructs (and associated equations) must be added on to them. The same is true for the categorical structures. Take strong monads, for example. The analysis of various effects in [21], makes it possible to axiomatize the additional structure2 that a strong monad T on C should be provided with.

• To model binary erratic nondeterminism, T should be equipped with a mor-phism 1 or>T(l + 1) satisfying equations for commutativity, associativity and idempotence.

• To model a ground storage cell, where S is the countable set of elements that can be stored, T should be equipped with a morphisms 1 ——

and Z^ggl updat>ey^ satisfying some equations given in [21]; and similarly for several cells.

• To model printing, where A is the countable set of characters that can be printed, T should be equipped with a morphism T1 ■

• To model raising of errors, where E is the countable set of errors, T should be equipped with a morphism eeE^ error>T0-

• To model I/O, where O is the countable set of messages requesting input, and message o E O requests an input from the countable set Io, the monad

T should be equipped with a morphism l'-^—1 for each o E O. (This generalizes the previous two examples. If Io is singleton, then o is a print-character. If Io is empty, the o is an error message.)

2 We assume that the category C has countable coproducts of a suitable kind. Below (Def. 2.1) we state this assumption precisely.

All these effects are instances of a general theory developed in [21,22]. This theory involves the notion of an algebraic operation, i.e. an operation d on terms such that

0{Mi}ieI to x. N = 6{Mi to x. N}ieI

where I is the (countable) arity of d and to means sequencing.

By contrast, as explained in [22], exception handling is not an algebraic operation. So how can we add exceptions to the monadic metalanguage? What equations should be imposed, and what is the resulting categorical structure? These questions will be answered in the first part of the paper (Sect. 2-5). We shall see that the categorical structure is actually a coalgebra for a certain comonad.

A large class of monads for exceptions is given by a monad transformer that takes a monad T to T(—+ E) [4]. Surprisingly, we shall prove that every monad for exceptions (on a category with equalizers) is of this form.

1.2 Adjunctions For Exceptions

CBPV is a fine-grain calculus that includes both call-by-value and call-byname as fragments [11,13]. It was shown in [14], that when we extend CBPV with a judgement for stacks (aka evaluation contexts), its categorical semantics is given by an adjunction. As an example, define an E-set to be a set X equipped with a function E —> X. Then the adjunction between the category of sets and that of E-sets gives a model of errors. A stack denotes a morphism of the second category, in this example, an E-set homomorphism. Intuitively. an evaluation context, applied to a term that raises an error, gives a term that raises an error.

As noted in [14], this theory cannot account for exception handling. Stacks that involve handlers may treat an error in a non-homomorphic way. The problem here is more severe than in Sect. 1.1, because exception handling actually invalidates some of the equational laws of CBPV with stacks. (A similar phenomenon is noted in [9]: exception handling invalidates some of the standard laws for continuations.) So what is the appropriate equational theory, and what is the resulting categorical structure? These questions will be answered in the second part of the paper (Sect. 6-7).

1.3 Combining Handling With Sequencing

Both of our questions rely on finding a reasonable set of equations for raising and handling of exceptions. Using conventional syntax for handling, this would

seem to be difficult. But in [2] a novel syntax was introduced for handle-sequencing :

M {to x. N, catch x. N'}

This means: first evaluate M. If it returns a value, bind x to that value and evaluate N. On the other hand, if it raises an exception, bind x to that exception and evaluate N'.

Many advantages of this syntax—which is equivalent, in the presence of sum types, to the traditional syntax—are discussed in [2]. But what is useful for us is that it is so similar to ordinary sequencing. So all we need to do is take the standard equations for sequencing and adapt them to this construct. This gives an elegant theory in both of the calculi we are considering: monadic metalanguage, and CBPV with stacks.

1.4 Theories and Categorical Structures

In the course of the paper, we present various equational theories and various categorical structures. We relate these with results asserting a "correspondence" between theory and structure. This asserts an equivalence between the category A of theories (where a theory consists of a signature and a congruence generated by the signature) and the category B of structures. See e.g. [14] for a precise statement of this equivalence in the specific case of CBPV adjunctions; this statement is easily adapted to the other cases. As explained there, the morphisms in both A and B are required to preserve structure on the nose; this is a flaw pervasive in categorical semantics, whose rectification is left to future work.

2 Monadic Metalanguage

The monadic metalanguage, with finite products and sum types, is shown in Fig. 1, along with syntax for exception raising. Here, pm abbreviates "pattern-match", and we use to for sequencing. Because the rules for 1 are analogous to those for x, we omit them. Throughout the paper, all constructs and equations that involve sequencing are marked because they are the ones that will need to be adapted when we add handle-sequencing into the language.

The equational theory is shown in Fig. 2. We omit the assumptions necessary to make each equation well-typed. Given a term r h M : B we write xM for the weakened term in the context r, x : A where A is some suitable type. This implies that x is not in r, because the identifiers in a context must be distinct. We thereby obviate the need for the traditional x E FV(M) conditions.

P.B. Levy /Electronic Notes in Theoretical Computer Science 158 (2006) 261—287 265

Types A ::= A, | 1 | A x A | A - A (I finite)

Tb x : A

(x : A) G T

T b M : A

T h return M : TA

T h M : TA T, x : A h N : TB F h M to x. N : TB

T h M : Ai

T h M) : £A,

F b m : V, I • x : . 1, \,:H (vï G /) r bpm M as {(¿,x).^}îe/

T h M : A T h M' : A' T h M : A x A' T, x : A, y : A' h N : B

T h (M, M') : A x A'

T h pm M as (x, y). N : B

T, x : A h M : TB T h Àx.M :A^B

T h M : A — B T h N : A

T h MJV : TB

Fig. 1. Syntax Of Monadic Metalanguage And Exception Raising

Laws of Sequencing

4 (return M) to x. N = N[M/x]

X M = M to x. return x 4 (M to x. N) to y. P = M to x. (N to y. xP)

3 -laws

pm (i,M) as {(i, x).Ni}iej = Nj[M/x] pm (M,M') as (x, y).N = N [M/x, M'/y] (Ax.M )N = M [N/x]

^-laws

N[M/z] = pm M as {(i, x). xN[(i, x)/z]}ieJ N [m/z] = pm M as (x, y). xyN [(x, y)/z] M = Ax.( xM x)

Fig. 2. Equations For Monadic Metalanguage

266 P.B. Levy /Electronic Notes in Theoretical Computer Science 158 (2006) 261—287

To interpret sum types, we adapt the following from [3,5].

Definition 2.1 Let C be a cartesian category, i.e. a category with distinguished terminal object and distinguished binary products.

(i) A distributive coproduct for a family of C-objects [Ai}iej is a cocone (V,{Ai '"'> y }»€/) such that, for every C-object X, the cocone (A' x V, { X x x V }iei) is a coproduct.

(ii) A distributive (resp. countably distributive) category is a cartesian category with a distributive coproduct for every finite (resp. countable) family of objects.

(iii) Let T be a strong monad on C.

• T has Kleisli exponentials when it is equipped, for every pair of C-objects A, B, with a representing object for the functor C(— x A, TB) : C°p —^ Set.

• T has countable products of Kleisli exponentials when it is equipped, for every countable family of pairs of C-objects {(Ai,Bi)}ieI, with a representing object for the functor nieI C(— x Ai,TBi) : C°P —> Set. (This clearly implies that T has Kleisli exponentials.)

Proposition 2.2 There is a theory/model correspondence (see Sectt. 1.4) between

• a theory of the monadic metalanguage

• a distributive category, together with a strong monad with Kleisli exponentials.

Remark 2.3 An infinitary variant of the metalanguage can be formed by including both countable sum types, and a fusion of function type and countable product types in the style of [15], to the calculus. There is then a correspondence between

• a theory of the infinitary monadic metalanguage

• a countably distributive category, together with a strong monad with countable products of Kleisli exponentials.

3 Exceptions

3.1 Raising Exceptions

We first treat the raising of exceptions, which requires an additional type exn, as shown in Fig. 3.1. Exception raising is an algebraic effect, in the sense of [20], and consequently its semantics is very simple—unlike that of

P.B. Levy /Electronic Notes in Theoretical Computer Science 158 (2006) 261—287 267

Types with Exceptions

a ::= eie!A, | 1 | A x A | A — A | exn (I finite) Exception Raising

T h M : exn T h raiseBM : TB

Raising Is Algebraic

4 (raise M) to x. N = raise M

Fig. 3. Syntax and Equations For Exception Raising In Monadic Metalanguage

exception handling. Indeed, the semantics of raise is determined by that of the computation x : exn h raise x : T0, because

raise^V = (raise0x)[V/x] to y. raiseBV

This is an instance of a general result [22]: an algebraic operation corresponds to a generic element. We define a semantic structure accordingly:

Definition 3.1 Let C be a distributive category, and let E be an object of C. A strong monad supporting E-raising is a strong monad T on C together with a C-morphism from E to T0.

The "monad constructor for exceptions" [4] provides the main class of examples.

Definition 3.2 Let C be a distributive category, with an object E. Let T be a strong monad on C. Then we define TE to be the strong monad T (—+ E).

Note that if T has Kleisli exponentials (resp. countable products of Kleisli exponentials) then so does TE.

Proposition 3.3 There is a theory-model correspondence (Sect. 1.4) between

• a theory of the monadic metalanguage with exception raising

• a distributive category C, with distinguished object E and a strong monad on C, with Kleisli exponentials, supporting E-raising.

3.2 Exception Handling—The Syntax

The changes required to obtain the monadic metalanguage with exceptions are shown in Fig. 4. We define

to x. N

M to x. N to be M

catch x. raise x

to x. return x

M catch x. N to be Ml

catch x. N j

We can then prove all the equations marked & (that are no longer needed as

axioms), and some assorted equations for handling:

(raise y)catch x. M = M [V/x] (1)

(return V)catch x. M = return V (2)

M= M catch x. raise x (3)

(Mcatch x.N)catch y.P Mcatchx.(Ncatch y. xP )(4)

((Mcatch w. return V) to x. N) catch y. P =

(Mcatch w. return V) to x. (Ncatch y. xP) (5)

((M to w. raise V)catch x. N) to y. P =

(M to w. raise V) catch x . (N to y. xP) (6)

We can also prove the following:

M{ to x. N, to x. N'} = ((M to w. return inl w)catch yreturn inr y) to z. pm z as {inl x. N, inr x. N'}

This shows handle-sequencing to be no more expressive (in the presence of sum types) than ordinary handling and sequencing. It is merely a syntactic convenience.

To give categorical semantics for exception handling will require more sophisticated machinery, which we now develop. But for the moment, note that TE always gives a model.

4 Coalgebras On Algebras

In this section, we review and develop some abstract theory of coalgebras.

Proposition 4.1 Let A ^ _L B be an adjunction with uniti] and counit.

e. Write L for the induced comonad (FG, e, F^G).

(i) There is a unique comparison K from the resolution (A, F, G, n) of L to the co-Eilenberg-Moore resolution (into the category of L-coalgebras). It

maps an A-object X to (FX, Fi]X), and a morphism X-*-X' to F f.

P.B. Levy /Electronic Notes in Theoretical Computer Science 158 (2006) 261-287 269

The following constructs and equations replace those marked 4 in Fig. 1-3.1.

r h M : TA r, x : A h N : TB r, x : exn h N' : TB V h M {to x. N, catch x. N'} : TB

to x. N (return MW >= N [M/x]

catch x. N' j

, to x. N , (raise MN' [M/x] catch x. N'

return x

Îto x. return x catch x. raise x

, to x. N \ I toy. P

(M ) y

catch x. NM I catch y. P'

to x. N {to y. xP, catch y. xP'} catch X. N' {to y. xP, catch y. xP'}

Fig. 4. Handle-Sequencing In The Monadic Metalanguage

(ii) Suppose A has all equalizers, and F preserves them. Then K has a right adjoint Q (not necessarily a comparison) and the counit of K H Q is an isomorphism.

Proof. This is proved in [1]. The right adjoint of K maps an L-coalgebra (Y, to the equalizer in A of

GY_ GFGY

Now suppose that (Tis a monad on a category M. We form the

following two adjunctions: M

(MT )l(t

Eilenberg-Moore

co-Eilenberg-Moore

This proceeds in three steps.

The first step is to form the Eilenberg-Moore resolution (M.T, GT, FT, eT) of T. This induces a comonad on MT, which we call L(T). Explicitly:

• it maps an object (X, 9) to (TX, ¡X)

• it maps a morphism (X, 9) (Y, 9') to (TX, (TY, ¡jlY)

• the counit at (X, 9) is (TX,

• the comultiplication at (X, 9) is (TX, ^iX)-^(T2X, f^iTX).

The second step is to form the co-Eilenberg-Moore resolution of this comonad. Explicitly:

• a coalgebra for L(T) is (X,9,4>), where (X, 0) is a T-algebra, and (A', 9)—^(TX, ¡jlX) is a T-algebra homomorphism such that

TX 6 X

X-TX commute

4> T4>

TX-r^T\X

a coalgebra homomorphism from (X, 9, $>) to (Y, 9', is a T-algebra homo-f

morphism (A', 9)-(Y, 9') such that

commutes

the forgetful functor (the left adjoint) maps an object (X, 9, to (X, 9)

and a morphism (A, 9, <j>) —U. (Y, 9', <j>') to /

the free functor (the right adjoint) maps an object (X, 9) to (TX, fiX, TnX)

and a morphism (A', 9) (Y, 9') to Tf

P.B. Levy /Electronic Notes in Theoretical Computer Science 158 (2006) 261—287 271

• the unit at (X, 0, is

The third step is to look at the unique comparison from our first resolution of L(T) to the co-Eilenberg-Moore resolution, which is terminal. It is a functor from M to the coalgebra category, mapping

• an object X to (TX, ¡X, TnX)

• a morphism X-*-Y to Tf.

We call this comparison K (T).

Proposition 4.2 Let (T, n, i) be a monad on a category M. Suppose M has all equalizers, and T preserves them. Then K(T) has a right adjoint Q, and the counit of K H Q is an isomorphism.

Proof. Since T preserves equalizers, the free algebra functor FT must do so too. We then apply Prop. 4.1 (ii). □

5 Monad Models For Exceptions

5.1 General Monads

In this section, let C be a distributive category, and E an object of it. We define MC to be the category of strong monads on C. We first recall the following result, mentioned in [7].

Proposition 5.1 Let T be a strong monad on C. Then TE is a coproduct of

T and - + E. The injection T-^TE is given at A by TA—^T(A + E).

The injection - + E->-TE is given at A by A + E—'l(A+EK T(A + E).

Now, in general, if E is an object of a category M such that every M-object U has a coproduct with E, then U ^ U + E gives a monad on M. So in particuar, we obtain a monad TC,E that maps T to TE. Its unit at T maps X to TXJ^T(X + E). The multiplication at T maps X to

T{{X + E) + E) T[id'inrl : T{X + E)

Furthermore, let us write M^ (resp. ML¿kl) for the full subcategory of MC consisting of strong monads with Kleisli exponentials (resp. countable products of Kleisli exponentials). Then TCeE restricts to a monad on Mk (resp. on Mckl), though the strong monad —+ E might lack Kleisli exponentials. We call this restricted monad TkEl

(resp. TfEl).

We can now formulate our main definition.

Definition 5.2 • A strong monad supporting E-exceptions on C is a coalgebra for L(TCE)■

• A strong monad with Kleisli exponentials (resp. with countable products of Kleisli exponentials) supporting E-exceptions is a coalgebra for C(IclE) (resp. L(TCf ))■

Let us unpack this definition.

Firstly, an algebra for the TC,E monad is precisely a strong monad T with a strong monad morphism from — + E to T, and such a strong monad morphism corresponds to a C-morphism E rais^ TO (by the general theory of algebraic-operations [22]). Thus, an algebra is a strong monad on C supporting E-raising. The algebra structure d is given at X by

T(X + E) T[''A''(raise-TD)] : rx.

A coalgebra for the induced comonad consists of a strong monad T supporting i^-raising, together with, for each C-object X, a morphism TX eX> T(X + E) that is natural in X, is strong monad homomorphic

n in\x,E

■T (X + E )

T2XS^±T(T(X + E) + E)

T ([id,n inrx,E])

T2(X + E)

ti(x+e)

TX x Y (e'Y)xV T(X + E) x Y

T (X x Y)

(eX xY )

tx+E,Y

T((X + E) x Y)

T (X x Y + E )

P.B. Levy /Electronic Notes in Theoretical Computer Science 158 (2006) 261-287

is a 7c,£i-algebra homomorphism

T(X + E)e-^T{{X + E) + E)

ÖX T[id,inr.Y+is,i;]

TX-^-*T(X + E)

and is coalgebraic

TX-^T{X + E)

id v TX

-^->T{X + E)

e(X+E)

T(X + E) TMx+ee~T((X + E) + E)

Proposition 5.3 The condition (7) is equivalent, in the presence of all the other equations, to the condition

fi-raise > rpQ

n inr0,E

T(0 + E)

5.2 Monad Semantics Of Exceptions

The above structure is precisely what we require to interpret handling. For given terms r h M : TA and r, x : A h N : TB and r, x : exn h N' : TB, the term M {to x. N, catch x. N'} denotes the composite

x T[A] FlXeM?|r] x T([A] + E)—^-T(|T] x ([A] + E)e)

Tim.m] T{ B]

It is then easy to see that all the equational laws of Fig. 2 are validated.

Conversely, we can construct such a coalgebra out of the syntax of handling. We define eA to be the congruence class of the term

x : TA h x {to y. return inl y, catch y. return inr y} : T (A + E )

and all the required commutativity diagrams follow from the laws. These two directions enable us to prove:

Proposition 5.4 There is a theory/model correspondence (Sect. 1.4) between

• a theory of the monadic metalanguage with exceptions

• a distributive category C, with a distinguished object E, and a strong monad, with Kleisli exponentials, supporting E-exceptions.

5.3 The Comparison Functor

Let us now unpack the comparison functor K(TCeE) defined in Sect. 4. It maps a strong monad T on C to the monad TE, so it is precisely the exceptions monad transformer.

Proposition 5.5 Let E be an object of a distributive category C. Suppose C has equalizers. Then the functors K(TC,E) and K(TkE and K(TfEl) each have a right adjoint, and, in each case, the counit of the adjunction is an isomorphism.

Proof. We have to check that the conditions of Prop. 4.2 are satisfied. Given a diagram of strong monads

the equalizer S—is computed pointwise. Kleisli exponentials are just equalizers of Kleisli exponentials for T and T', and similarly for countable products of Kleisli exponentials. Preservation by TC,E is trivial. □

Corollary 5.6 Let T be a strong monad on C supporting E-exceptions. If C has equalizers, then T = T'E for some strong monad T' on C, possessing Kleisli exponentials (resp. countable products of Kleisli exponentials) if T possesses them.

We note that T' might not be unique up to isomorphism. For example.

let C be Set, let E be 1, let T' be the monad (--> 0) ^ 0, and let T'' be

the unit monad (mapping everything to 1). Then T E and T'E are isomorphic (they are the unit monad), but T''0 = T'0.

We have now characterized all monads on Set that model exceptions and validate the laws of Fig. 2. We next look at some non-examples. Here are two monads on Set, supporting E-raising, that do not support E-exceptions in general:

(i) [6] the monad mapping X to S ^ ((S x X) + E), where S is some set

(ii) the monad mapping X to (S x ((S x X) ^ R)) ^ R, where R is some set and S is E ^ R.

The second example has been provided independently by Andrzej Filinski and Hayo Thielecke [personal communication] as a model for the catch and escape facility provided in NJ-SML.

In each case there is a candidate interpretation for handle-sequencing. Suppose r h M : TA and r, x : A h N : TB and r, x : exn h N' : TB. Then, we define [M {to x. N, catch x. N'}]] to map p G [r]] to

(i) the function mapping s G S to

• ([N](p, x ^ b))s' if ([M]p)s = inl (s',b)

• ([n'Kp, x ^ e))s if ([M]p)s = inr e.

(ii) the function mapping s G S and k G (S x [B]) ^ R to

([M]p)((Ae.(([N']p)(s,k))), (X(s',b).(([N]p)(s',k))))

Corollary 5.6 suggests that these interpretations do not (in general) validate the equations of Fig. 4. This can be checked directly: (i) breaks equation (5), and (ii) breaks (3). Filinski has also shown [personal communication] that (3) is broken, as an observational equivalence, by catch and escape. Two alternative conclusions may be drawn:

• these monads are inappropriate for modelling exceptions, and the constructs they model (such as catch and escape) are unnatural

• the laws in Fig. 4 are too demanding, for exceptions in general.

6 Review of Call-By-Push-Value With Stacks

A model of the monadic metalanguage with exceptions is still a model of the monadic metalanguage, albeit with extra structure. By contrast, in the case of CBPV with stacks, to which we now turn, the addition of exceptions necessitates a genuinely different structure. We first review CBPV. Our account is for infinitary CBPV; replace "countable" by "finite" throughout for the finitary version.

CBPV has two disjoint classes of terms: values and computations. It likewise has two disjoint classes of types: a value has a value type, while a computation has a computation type. For clarity, we underline computation types. The types are given by

value types A ::= UB\ Y,ieiAi I 1 M x A

computation types B ::= FA \ Y\.iei—i I A ^ B_

where I can be any countable set (finite, in finitary CBPV). The meaning of F and U is as follows. A computation of type FA produces a value of type A. A value of type UB_ is a thunk of a computation of type B_, i.e. the computation is frozen into a value so that it can be passed around. When later required, it can be forced i.e. executed.

As an example model, suppose we have a monad T on a cartesian closed category C with countable coproducts and products. Then each value type denotes a C-object, and each computation type a T-algebra, in the evident way. U and F follow the Eilenberg-Moore adjunction, whilst Y\.iei and ^ denote product algebra and exponential algebra.

Like in call-by-value, an identifier in CBPV can be bound only to a value, so it must have value type. We accordingly define a context r to be a sequence

xo : Ao,...

> xn— 1 : An—1

of distinct identifiers with associated value types. We write r hv V : A to mean that V is a value of type A, and we write F bc M : B_ to mean that M is a computation of type B_.

In the monad semantics, a value r hv V : A denotes a C-morphism from [F] to [A], and a computation T bc M : B_ denotes a C-morphism from [F] to the carrier of [£>].

The terms of CBPV are given in Fig. 5. The symbol' represents application in reverse order.

A third judgement is bk K : C_. This comes from the CK-machine of[14], and means that K is a stack or evaluation context of type C_, with a S-typed hole. We do not treat the CK-machine in this paper, but give the typing rules for stacks.

For the monad semantics, given strong monad T on C, we define a homo-

morphism from T-algebra (Y, 0) to T-algebra (Z, over C-object X to be a

C-morphism X x Y-satisfying

X x TV t(X'Y): T(X x Y)-T-^TZ

X x Y--f-

A stack r|S bk K : C_ then denotes a homomorphism from [S] to [C] over

The complex values are an extension of pure CBPV that are needed to achieve theory/model correspondence, though they complicate operational semantics. It is shown in [10] that this extension is conservative on computa-

value types A

computation types R

Values and Computations

r x : A, r I-v x : A

UB I I 1 I A x A

FA I HçjBi I A^B

Y V : A r, X : A bc M : R Y bc let y be x. M : B

r bv y : A

r bc return y : FA

r bc M : FA r, x : A bc N : B Y bc M to x. N : B

r\-c M : B

r bv thunk M : UB

Yh~y V :UR Y bc force y : B

Y V \ Aî rbvT/:^elA r.x:.l, ' \1}:R ¡\'/C /! ï G I -

r bv {î, V) : £A,

r bv v : A r bv v' : A

Y bv (V, V'):Ax A

I bc Mi : R, (V« G I) I' A {i.M,},. / : J {, ,R,

rb pm V as {(?,, x).Mi}ieI : R

Y bv V : A x A' Y, x : A, y : A' bc M : R Y bc pm y as (x,y).M : R

r M : UieiR-i

Y bc r.\l : I!

T, x : ib M : R Y bc Ax.M :A^B

Stacks

r|Çbknil :Ç

Y bv T/ : A Y bc M : A ^ R Y bc y M : B

Y,x: Ahc M : R Y\Rhk K : C Y\FA bk to x. M :: K : Ç

r|Ri bk K : C_ I'll ,R, k>y- i<:L

Y bv V : A Y\R bk K : C T\A^B\-kV::K:Ç

Fig. 5. Terms of CBPV with stacks

tions. We can similarly add complex stacks, as explained in [14]. The syntax of complex values and complex stacks is shown in Fig. 6.

Given a computation T bc M : B_ and a stack bk K : C_, we obtain a computation T bc M • K : C by dismantling K on C_, defined by induction on K in the obvious way.

Given a stack bk K : G_ and T|£7 bk L : D_, we can concatenate K and L to give bk K-W-L : D_, defined by induction on K in the obvious way.

The equational theory for CBPV is shown in Fig. 7 (with the same conventions as Fig. 2), and the additional law for exception raising in Fig. 8. Here are some consequences:

M • K = M to x. ((return x) • xK) M = M to x. return x (M to x. N) • K = M to x. (N • K) (M to x. N) to y. P = M to x. (N to y. P) \{i.(M to x. Ni)]ieI = M to x. \{i.Ni}ieI \y.(M to x. N) = M to x. Xy.N

(raise V) • K = raise V A{i.raise V}ieI = raise V Xx. raise V=raise V

Definition 6.1 Let D be a category. A right D-module is a functor O : D —> Set. Explicitly

• it provides for each A a set OA of "morphisms", an element of which is written —

• we can compose —^A with A—^ B to obtain 9'h> A

• this composition satisfies associativity and right-identity laws.

Definition 6.2 Let C be a category.

A locally C-indexed category is a strictly C-indexed category D in which all the fibres have the same objects (ob D) and all the reindexing functors are identity on objects; equivalently, a [C°P, Set] enriched category.

Let D be a locally C-indexed category. A right D-module consists of

• for each X e ob C and Y_ e ob V, a small set OxY_, an element of which we call an O-morphism over X to Y_ and write —V"—

• for each and —V"— a reindexed O morphism Y_

• for each and Y—^-Y! a composite O morphism g'x> Y_[

Complex Values

r hv V : A r, x : A hv W : B T hv let Vbex.W:B

rh'V: T,x : Aj\~v Wj : B (Vi € I)

rhvpm T/ as {(i,x).Wi}ieI : B

r hv V : A x A' r, x : A, y : A' hv W : B r hv pm V as (x,y).W : B

Complex Stacks

r hv y : A T,x.A\B bkii : C T\B hk let V be x. K : C

rhv7: ¿2ieIA r, x : AIR hk Kt : C (Vi G I) r|ßbkpm T/ as {(i, x).Ki}i€l : C

T^vV:AxÄ r,x: A,y : A'\B^kK : C r|ßhkpm V as (x,y).K :C

T\C^kK:B V\BY-kL:D r|C hk K where nil is L : D

r\C hk IQ : B, (Vi € I) r|YlieiM* r|C hk {Ki where i :: nil}feJ is L : D

r, x : A\C_ hk K : B_ T\A ->• ßhk L : D r|C hk K where x :: nil is L : D

Fig. 6. Complex Values and Stacks

280 P.B. Levy /Electronic Notes in Theoretical Computer Science 158 (2006) 261—287

ß-laws

let V be x. Q = Q[V/x] K where nil is L = K-—L

pm { î,V) as {{i, x).Qi]ieI = Qî[V/x]

pm {V,V') as {x,y).Q = Q[V/x,V'/y] force thunk M = M * (return V ) to x. M = M [V/x] I 'A{i.Mi}iei = Mî {K.i where i :: nil}ieI is î :: L = Kî-—L

V'Ax.M = M [V/x] K where x :: nil is V :: L = K[V/x]-—L

^-laws

Q[y/z] = pm y as {{i, x). *Q[(i, x)/z]}ieJ Q[V/z] = pm V as (x, y). xyQ[(x, y)/z] V = thunk force V X K ++L = to x. ((return x) • K) :: L M = \{...,i.ilM,...} K ++L = {(K-H-i :: nil) where i :: nil}ieI is L

M = Ax.(x' xM) K-H-L = (xK-Hx :: nil) where x :: nil is L

Fig. 7. Equational laws for CBPV + stacks

Types with Exceptions

value types computation types

Exception Raising Raising Is Algebraic

A ::= UB | £feJA \ 1 \ A x A \ exn R::= FA \ Ui€iM* I A^B

rhv V : exn

T hc raiseBM : B

(raise V) to x. M = raise V

Fig. 8. Syntax and Equations For Exception Raising In CBPV

P.B. Levy /Electronic Notes in Theoretical Computer Science 158 (2006) 261—287 281

satisfying right-identity, associativity and reindexing laws.

Various equivalent versions of these definitions are given in [14]. Definition 6.3 A CBPV judgement model consists of

• a cartesian category C

• a locally C-indexed category D

• a right D-module O.

Given such a structure, we interpret

• a value type or context by a C-object

• a computation type by a D-object

• a value T hv V : A by a C-morphism [T] {A}

• a stack T\B bk KG by a D-morphism [S] [C]

• a computation I' bc M : C_ by an 0-morphism J^r]

This structure interprets the connectives x and 1. To interpret the remaining connectives, we require the following.

Definition 6.4 In a CBPV judgement model (C, D, O),

UB^ a right adjunctive for a D-object B_ is a C-object V and an 0-morphism f°ye > II, such that the functions

C{X, V) —> OxB for all X

f^f* force are isomorphisms

FA a left adjunctive for a C-object A is a D-object V and an O-morphism ret^rn> V, such that the functions

Vx(V, Y) OxxaV for all X, Y

h -—> (n'lAreturn); (n*x,Ah) are isomorphisms

Ai a distributive coproduct for a family [Ai}iej of C-objects is a C-object V and, for each i e I, a C-morphism Ai '"' > V, such that the functions C(X x V,Y) —> Uie! C (X X Ai, Y) for all X, Y OxxvY TlreiVxxAX for all X, Y

VXxv(Y, Z) nizPxxA* QL, Z) for all X, Y, Z f^\i,((Xxmryf)

are isomorphisms

nieIBi a product for a family {B^j^i of P-objects is a P-object V_ and, for each i E I, a P-morphism V B4 , such that the functions

OxV^U,, ,OxR, for all X

T>x(Y, V) UicPxiY, B,) for all X, Y_ h \i.(h;()*ni) are isomorphisms

A —i? an exponential from a C-object A to a P-object B is a P-object V_ and a P-morphism V > B_, such that the functions

OxV —> OxxaR for all X

T>x(Y, V) VxxaQL, B) for all X, Y_

h >—► (fA',lev)

are isomorphisms.

Definition 6.5 A CBPV adjunction is a CBPV adjunction model with all left adjunctives, all right adjunctives, all countable products, all countable distributive coproducts and all exponentials.

For example, suppose T is a strong monad on a countably distributive category C, and all countable products of, and exponentials to, carriers of T-algebras exist in C. Then the Eilenberg-Moore resolution of T is a CBPV adjunction. Many other examples are given in [14,13]

Proposition 6.6 [14] There is a theory/model correspondence (Sect. 1.4) between

• a theory of CBPV with stacks (including complex values and complex stacks)

• a CBPV adjunction.

To interpet exception raising, we again use the "generic element", as in Sect. 3.1.

Definition 6.7 Let E be an object of a cartesian category C. A CBPV adjunction supporting E-raising is a CBPV adjunction (C, D, O) together with an 0-morphism rai^> FO •

Proposition 6.8 There is a theory/model correspondence between

• a theory of CBPV with stacks and exception raising

• a cartesian category C with object E and CBPV adjunction supporting E-raising.

7 CBPV With Handle-Sequencing

Fig. 9 shows how to add handle-sequencing to CBPV with stacks and exception raising. Given a strong monad T on C, we interpret values and computations as before, using the monad TE. In particular, FA denotes the free TE-algebra on A, and UB denotes the carrier of [5]. But a stack does not denote a TE algebra homomorphism, because raise V • K might not raise V. It has to denote a T-algebra homomorphism. More precisely, if Y_ = (A', 6) is a TE-algebra, write pY_ for the T-algebra (A', (Tinlx^; 9)). Then a stack r|5 bk K : G_ denotes a T-algebra homomorphism from p{Bj to p{CJ over ¡T],

We see in this class of examples that F and U do not describe an adjunction between values and stacks. We can see this in the equational theory too. Define M to x. N as in Sect. 2, and similarly define to x. N :: K to be

i to x. N }

catch x. raise x

Then one of the equations that appears in Fig. 7 and is valid in any CBPV adjunction, viz.

K—L = to x. ((return x) • xK) :: L

ceases to be valid. To see this, suppose that V is a closed value of type exn, take L to be nil , and let K be to x. return (). When we dismantle the two sides onto raise V, then the LHS returns the value (), whereas the RHS raises exception V.

Thus, in the presence of exceptions, the type FA is not a left adjunctive for A. To model F, we need to generalize the notion of left adjunctive.

Definition 7.1 (i) Let (C, D, O) be a CBPV judgement model, and let E be an object of C. A left E-adjunctive for a C-object A consists of a P-object V, an 0-morphism retu4rB V and an 0-morphism V such that the functions

Vx(V, Y) OxxaV x OxxeY for all A, Y_ h 1—► (((nx,Areturn); (п*x,Ah)),

((nX,Araise);(nX ,Ah)))

are isomorphisms.

(ii) Let E be an object of a cartesian category C. A CBPV E-adjunction is a CBPV judgement model (C, D, O) with all left E-adjunctives, all right adjunctives, all countable products, all countable distributive co-

The following constructs and equations replace those marked $ in Fig. 5-7.

r bc M : FA T,x: Ahc N : B F, x : exn bc N' : B r bc M {to X. N, catch x. N'} : B

r, x : A bc M : B F, x : exn bc M' : B T\B bk K : C

products and all exponentials. We write FA for (the vertex of) the left ^-adjunctive of A, and likewise for the other operations on objects.

(iii) Let E' and E be objects of a cartesian category C. A CBPV E'-adjunction supporting E-raising is CBPV E'-adjunction (C, D, O) together with an 0-morphism ^^ FO ■

Note that a CBPV 0-adjunction is just a CBPV adjunction.

Proposition 7.2 There is a theory/model correspondence between

• a theory of CBPV with stacks and exceptions

• an object E of a cartesian category C, and a CBPV E-adjunction.

We relate this to strong monads as follows.

Definition 7.3 Let E be an object of a cartesian category C, and let (C, D, O) be a CBPV E-adjunction. Then C is countably distributive, and we obtain a CBV strong monad on C, supporting E-exceptions: on objects it is given by A ^ UFA, and the rest is evident.

Another way of seeing this construction is as a translation from the monadic metalanguage with exceptions to CBPV with exceptions.

T\FA bk {to x. M, catch x. M'} :: K : Ç

Fig. 9. Exception Handling In CBPV With Stacks

We can also translate CBPV with exceptions to CBPV without exceptions, so we can convert an adjunction into an E-adjunction. More generally, an E' adjunction can be converted into an E' + E adjunction:

Definition 7.4 Let E' and E be objects in a cartesian category C, and let A = (C, O, D) be an E'-adjunction. We construct an E' + E adjunction Ae = (C, D', O') as follows.

An object of V is a D-object B_ together with an 0-morphism — A D'-morphism (B_,r)—is a D-morphism B_—^-C.

An O'-morphism -j- (B, r) is an 0-morphism —'

Distributive coproducts are unchanged. The right adjunctive of (B_, r) is UB_.

The product of {B^ ri}ieI is (ELe/i^ s) where s; 0*7^ = ru The exponential from A to (B, r) is (A B_, s) where ir*A E,s; 7Eev = 7Er The left E + E' adjunctive of A is (F(A + E), \m*a ereturn).

Proposition 7.5 If T is the strong monad obtained from E'-adjunction A, then the strong monad obtained from (E' + E)-adjunction AE is TE.

Conversely. suppose we are given an E adjunction. We can obtain an ordinary adjunction supporting E-raising by restricting to those stacks that are "homomorphic" in exception raising. More generally, given an E' + E adjunction. we can obtain an E' adjunction:

Definition 7.6 Let E' and E be objects in a cartesian category C, and let (C, O, D) be an E' + E adjunction. We form an E' adjunction (C, O, D') supporting E raising, as follows. D' has the same objects as D. A D'-morphism B_—is a D-morphism B_—which is "homomorphic for E" i.e.

z v as a diagram over X x E commutes.

n'X ^raise n'X ^raise

b-;—t^C

The left E' adjunctive of A is FA with inlE' Eraise. All the other connectives are unchanged. This monad supports E-raising via the morphism

inrE' eraise.

As an example, suppose we take the monad semantics of CBPV with stacks, using strong monad T on category C. If we apply the construction in Def. 7.4, we obtain the semantics of CBPV with stacks and exception handling described above, where a computation object is a TE-algebra but a stack is

286 P.B. Levy /Electronic Notes in Theoretical Computer Science 158 (2006) 261-287

a T-algebra homomorphism. If we then apply the construction in Def. 7.6, then we get the monad semantics for errors, where a computation object is a TE-algebra and a stack is a TE-algebra homomorphism.

Acknowledgement

I thank A. Filinski and H. Thielecke for their help.

References

Beck, J. M., Triples, algebras and cohomology, Reprints in Theory and Applications of Categories 2 (2003), pp. 1-59.

Benton, N. and A. Kennedy, Exceptional syntax, Journal of Functional Programming 11 (2001), pp. 395-410.

[3] Carboni, A., S. Lack and R. F. C. Walters, Introduction to extensive and distributive categories, J. of Pure and Applied Algebra 84 (1993), pp. 145-158.

[4] Cenciarelli, P. and E. Moggi, A syntactic approach to modularity in denotational semantics, in: CTCS 1993, 1993.

[5] Cockett, J. R. B., Introduction to distributive categories, Mathematical Structures in Computer Science 3 (1993), pp. 277-307.

[6] Filinski, A., Representing layered monads, in: Proc., 26th ACM SIGPLAN-SIGACT Symp. on Principles of Programming Languages, 1999, pp. 175-188.

[7] Hyland, J. M. E., G. D. Plotkin and A. J. Power, Combining effects: Sum and tensor (2006), to appear in Theoretical Computer Science.

[8] Laird, J., A fully abstract game semantics of local exceptions, in: Proc. of the 16th Annual IEEE Symp. on Logic in Computer Science (2001), pp. 105-114.

[9] Laird, J., Exceptions, continuations and macro-expressiveness, LNCS 2305 (2002).

10] Levy, P. B., Call-by-push-value: Decomposing call-by-value and call-by-name, submitted.

11] Levy, P. B., Call-by-push-value: a subsuming paradigm (extended abstract), in: J.-Y. Girard, editor, Typed Lambda-Calculi and Applications, LNCS 1581, 1999.

12] Levy, P. B., Possible world semantics for general storage in call-by-value, in: J. Bradfield, editor, Proceedings, 16th CSL, LNCS 2471 (2002).

13] Levy, P. B., "Call-By-Push-Value. A Functional/Imperative Synthesis," Semantic Structures in Computation, Springer, 2004.

14] Levy, P. B., Adjunction models for call-by-push-value with stacks, Theory and Applications of Categories 14 (2005), pp. 75-110.

15] Levy, P. B., Jumbo X-calculus (2006), to appear in Proc., 33rd ICALP, in LNCS.

16] Levy, P. B., A. J. Power and H. Thielecke, Modelling environments in call-by-value programming languages, Inf. and Comp. 185 (2003), pp. 182-210.

17] Mac Lane, S., "Categories for the Working Mathematician," Graduate Texts in Mathematics 5, Springer, New York, 1971, ix+262 pp.

18] Moggi, E., Computational lambda-calculus and monads, in: LICS'89, Proc. 4th Ann. Symp. on Logic in Comp. Sci., IEEE, 1989, pp. 14-23.

[19] Moggi, E., Notions of computation and monads, Inf. and Comp. 93 (1991).

[20] Plotkin, G. and J. Power, Adequacy for algebraic effects, LNCS 2030 (2001).

[21] Plotkin, G. and J. Power, Notions of computation determine monads, in: Proc., Foundations of Software Sci. and Comp. Struct., 2002, LNCS 2303 (2002).

[22] Plotkin, G. D. and A. J. Power, Algebraic operations and generic effects, Applied Categorical Structures 11 (2003), pp. 69-94.