Available online at www.sciencedirect.com

ScienceDirect

Electronic Notes in Theoretical Computer Science 319 (2015) 403-421

www.elsevier.com/locate/entcs

Stateful Runners of Effectful Computations

Tarmo Uustalu1

Institute of Cybernetics, Tallinn University of Technology, Akadeemia tee 21, 12618 Tallinn, Estonia

Abstract

What structure is required of a set so that computations in a given notion of computation can be run statefully with this set as the state set? For running nondeterministic computations statefully, a resolver structure is needed; for interactive I/O computations, a "responder-listener" structure is necessary; to be able to serve stateful computations, the set must carry the structure of a lens. We show that, in general, to be a stateful runner of computations for a monad corresponding to a Lawvere theory (defined as a set equipped with a monad morphism between the given monad and the state monad for this set) is the same as to be a comodel of the theory, i.e., a coalgebra of the corresponding comonad. We work out a number of instances of this observation and also compare runners to handlers.

Keywords: effects, monads, Lawvere theories, comodels, state monads, handlers

1 Introduction

This paper is about Moggi's monad-based and Plotkin and Power's Lawvere theories based approaches to effectful computation [8,10].

Given a monad (T, n, m), a computation of a value in X is an element of TX. Computations are there to compute values, so we consider it natural to wish to extract these values, to run computations. Ideally, we might want to have at our disposal a polymorphic function 6 : ^X. T X — X for extracting values from computations, but this is generally too much to ask (although it is possible, e.g., for writer monads).

However we can often produce a value, if we are allowed to rely on some input— think of it as an initial state—drawn from some set C with suitable structure. For example, if we have a finitely nondeterministic computation in the sense of a binary wellfounded leaf tree, a bitstream can be used to identify a leaf. As running should reasonably be compositional in the sense that running the sequence of two computations should be the same as composing two runs, a run should not only

1 tarmo@cs.ioc.ee

http://dx.doi.Org/10.1016/j.entcs.2015.12.024 1571-0661/© 2015 The Author. Published by Elsevier B.V.

This is an open access article under the CC BY-NC-ND license (http://creativecommons.Org/licenses/by-nc-nd/4.0/).

depend on an initial state, but also return a final state (that can serve as the initial state for another run). In the case of nondeterminism and bitstreams, the final state could be the remainder of the bitstream provided as the initial state. So in general we might want to look for a polymorphic function 6 : yX.TX TC X where (TC,nC) is the state monad for C as the state set. The compositionality we want amounts to 6 being not just a natural transformation, but a monad morphism.

In this paper, we answer the question of when a set C can be used to run computations in a monad (T,-q,^) statefully, assuming that the monad corresponds to a Lawvere theory. The answer is: C has to carry a comodel of the Lawvere theory (i.e., a coalgebra of the corresponding comonad). We spell out a number of instances of this generality, for nondeterminism, interactive I/O and stateful computations. This is an easy exercise, but the results are quite instructive, we find. For some versions of nondeterminism, for instance, runners can only recover a part of the information in a given computation; other versions of nondeterminism admit only trivial runners that reveal nothing about the computation. So some variations of nondeterminism are inherently more operational than others.

Runners are somewhat similar to handlers, but one bigger difference is that runners are polymorphic in the value set. For example, handling allows one to extract a value from a nondeterministic computation (a binary wellfounded leaf tree) over a specific value set that carries a binary operation by folding this operation over the leaf labels. (If for us a nondeterministic computation is a nonempty list of values, this operation must be associative.) Running does not allow such things. In our view, the pragmatics of handlers and runners are different: handlers are a programming language construct, but runners are compilation schemes.

The paper is organized as follows. In Section 2, we review the few basic facts about Lawvere theories, models and comodels that we need. In Section 3, we show that stateful runners for a monad corresponding to a Lawvere theory are in a bijection with comodels of the theory (coalgebras of the corresponding comonad). We also compare this observation to a fact about monad morphisms to continuation monads—a different type of runners. In Section 4, we work out the instances for nondeterminism, interactive I/O and stateful computation. Just before concluding, in Section 5, we compare runners to handlers.

2 Lawvere theories, models, comodels

We begin by reviewing the most basic definitions and facts about finitary Lawvere theories and models (for a proper exposition, see, e.g., [6]) as well as Power's comodels [13,11]. Countable Lawvere theories and K-ary Lawvere theories for a regular cardinal k are defined analogously.

Lawvere theories

A (finitary) Lawvere theory is given by a small category L with finite products and a functor L : Fop ^ L that is identity on objects and strictly preserves the finite products of Fop.

Here F is the category of finite cardinals, i.e., the skeleton of the category of finite sets. It is a strict monoidal category wrt. finite coproducts, in fact it is the free such category on the one-object category.

A theory can (non-uniquely) be specified by a presentation, i.e., by some subset of the maps OPj : Ij ^ Oj of L (operations) from which all other maps are definable together with some subset of the commuting diagrams LHSk = RHSk of L (equations) from which all other commuting diagrams follow.

Notice that one can always do with operations of arities I ^ 1 only. As O = Uoeo 1, any operation OP : I ^ O can be replaced with O many operations OP° : I ^ 1 via OP° = ino o OP and OP = (£]oeO OPo) oV. 2 )

Models

A model of a theory (L, L) is given by a functor |—] : L ^ Set that preserves the finite products of L (non-strictly).

To give a model of (L,L), it suffices to specify a set

A = 11]

since, for any other object Y, we have ¡Y] = ¡U^eY 1] = n^eY 11] = 11] — Y3 together with functions

opj = A-1 ¡OPj] : Oj x (¡1] - Ij) ^ ¡1]

since, for any other map f, ¡f] is then uniquely determined by functoriality and preservation of finite products. Moreover, any set A with functions opj : Oj x (A — Ij) ^ A defines a model, provided that the equations lhsk = rhsk hold for the derived functions lhsk, rhs k.

Theories and monads

A theory defines a unique monad whose algebras are essentially the same as its models.

The monad corresponding to a theory (L, L) is a quotient of a free monad. The underlying functor is

TX = T0 X/~*x where T0 X is the set defined inductively by

s : x o : Oj f : T0 X - Ij

var x : T0 X opj (o,f): T0 X (so that, in a more compact notation, Tq X = ¡iZ. X + \Jj Oj x (Z ^ Ij)) and

2 We write maps of L in terms of the operations of the presentation, maps of F, the product bifunctor of L, which we denote + (sic!) to agree with the notation for the coproducts of F, and composition of L. Note that maps of F have their directions reversed in L, so in0 : 1 O in F, but in0 : O 1 in L etc.

3 To avoid the need to explicitly use the symmetry of x in the examples, we will use two exponential functors ^ and think of — ^ Y as the right adjoint of Y x — and Y ^ — as the right adjoint of -xY.

is a binary relation on T0 X defined inductively by

y i : Ii.fi -x f' i _

0Pj (o, f) -X opj (o, f 0 ihsfe (o, f) -X rhsfe (o, f)

The unit n is var and the multiplication f is defined recursively by f (var t) = t and f (opj (o, f)) = opj (o, M.fj, (f i)).

Algebras of (T, n, f) are essentially the same as models. A model (A, (opj : Oj x (A ^ Ij) ^ A)j) and an algebra (A,a : TA ^ A) are interdefinable recursively by a (var x) = x and a (opj (o,f)) = opj (o,Xi.a (f i)) and by opj (o, f) = a (opj (o,Xi. var (f i))).

The monad corresponding to a theory is finitary. And any monad corresponds to at most one theory in this fashion.

Comodels

We are now prepared to discuss Power's notion of comodels.

A comodel of a theory (L, L : Fop ^ L) is given by a functor {{—)) : Lop ^ Set that preserves the finite coproducts of Lop (recall that a model was a functor from L preserving its finite products).

To give a comodel, it suffices to specify a set

C = «1))

since «X)) = «UxeX 1)) = UxeX ((1)) = «1)) x X, together with functions

opj = «OPj)) : «1)) x Oj ^ «1)) x Ij

where we often split opj as «opñj, opSj) (with n and s mnemonic for "next" and "show"). Also, any set C with functions ~opj : C x Oj ^ C x Ij defines a comodel, provided that the equations Ihsk = rhsk hold for the derived functions Ihsk, rhsk.

Theories and comonads

Besides defining a (finitary) monad whose algebras are the same as models, a theory also defines a comonad with the property that comodels of the theory are the same as coalgebras of the comonad.

The comonad corresponding to a theory (L, L) is a subcomonad of a cofree comonad. The underlying functor is defined by

DX = Do X | okx

where D0 X is a set defined coinductively by4

d : D0 X d : Do X o : Oj d : Do X o : Oj var d : X opñj (d, o) : D0 X opSj (d, o) : Ij

4 We write coinductive definitions in a destructor-based fashion (as opposed to the constructor-based style commonly used in proof assistants), as this works more smoothly.

(so that, in a more compact notation, D0 X = vZ. X x nj (Oj ^ Z x Ij)) and okx is a predicate on D0 X defined coinductively by

okX d _okx d_ _okx d_

okx (opnj (d, o)) ihsnk(d, o) = rhsnk(d, o) ihssk(d, o) = rhssk(d, o)

The counit e is var. The comultiplication 5 is defined corecursively by var (5 d) = d, opnj (5 d, o) = 5 (opn j (d, o)), opsj (5 d, o) = ops j (d, o).

A comodel (C, opj : C x Oj — C x Ij)j) is interdefinable with a coalgebra (C, 7 : C — DC) corecursively by var (7 c) = c, opnj (7 c, o) = 7 (opn j (c, o)), opsj (7 c, o) = ~opsj (c, o), and by opñj (c, o) = Var (opnj (7 c, o)), ~opsj (c, o) = opsj (7 c, o).

The comonad corresponding to a theory in the above fashion is in general non-finitary. Also, one comonad can correspond to many theories. (E.g., all theories with at least one nullary operation (op : 0 ^ O with O = 0) have the initial comonad (D X = 0) as the corresponding comonad.)

3 Stateful runners = comodels

We are prepared to prove the theorem that this paper revolves around. We prove that a stateful runner is the same as a comodel.

Proposition 3.1 Given a Lawvere theory (L,L), let (T,-q,^) be the monad corresponding to the theory. Given a set C, let (TC,r¡C) be the state monad for C. There is a bijection between monad morphisms from (T,n, to (TC,nC) and comodels on C (i.e., coalgebras of the comonad (D,e,5) corresponding to (L,L)).

Proof. Let the Lawvere theory (L, L) be given by operations OPj : Ij ^ Oj and equations lhs^ = RHS^. The corresponding monad (T,-q,^) is then constructed as described in the previous section.

Given a comodel (opj : C x Oj C x Ij)j, the monad morphism 6 : yX.TX ^ (C x X) ^ C is defined by recursion on t : T0 X by

6x (var x) = Xc. (c,x) 6x (°pj f)) = Xc. 6x (f (opSj o)) (opñj o))

For this definition to be legitimate, 6x must send ^x-related computations in T0 X to equal computations in TC X. This is proved by induction on the proof of t ~x t from lhsnk = rhsnk and lhssk = rhss k.

The unit preservation law of a monad morphism holds trivially. The multiplication preservation law is a "substitution lemma" that is proved by induction on t : To (To X).

In the converse direction, given a monad morphism 6, we define the comodel (OPj)j by

~opj (c, o) = 6I} (opj (o, Xi. var i)) c

The equations Ihsnk = rhsnk and Ihssk = rhssk follow from Ox sending ^x-related computations in T0 X to equal computations in TC X.

The roundtrip from a comodel to a monad morphism and back is straightforwardly identity. The other roundtrip is identity thanks to naturality of O. □

We compare this theorem to the following well known theorem (see, e.g., [5]) about running with continuations.

Proposition 3.2 Given a monad (T,n,i) and a set A. Let (TA,nA,iA) be the continuation monad for A. Monad morphisms O from (T,n,i) to (TA ,nA ,iA) are in a bijection with (T,n, ¡)-algebra structures a on A.

Proof. Given an algebra structure a : T A — A, the monad morphism O : iX. T X -(A ^ X) ^ A is defined by Ox t = Xf. a (T f t); the laws of a monad morphism follow from the laws of an algebra.

In the converse direction, given a monad morphism O, the corresponding algebra structure a is defined by at = Oa t idA; the laws of an algebra follow from the laws of a monad morphism.

The roundtrip from an algebra to a monad morphism and back is straightforwardly identity. The proof of the other roundtrip being identity relies on the naturality of O. □

Notice that in the first theorem we use a Lawvere theory to relate a monad and a comonad (however the Lawvere theory is determined by the monad). The second theorem can be stated without referring to a Lawvere theory.

A more important difference is this. Given any monad, for any value set X, one can find a runner with continuations (A, O) such that Ox is mono, i.e., all information about a computation over a given value set X in the given monad is retained in its counterpart in the continuation monad. Indeed, for any X, invoking the free algebra (T X, ¡ix), we have Ox trjx = t.

In the case of stateful running, it is much more difficult to achieve Ox being mono. As we will see shortly, it is easy to construct examples where no state set C is sufficient to recover computations over a given value set X.

Both theorems can be strengthened to isomorphisms of categories; we skip the details here.

4 Instances

4.1 Nondeterminism

Let us see the above proposition at work on the example of various finite nondeter-minism monads as well as the partiality monad.

Finite nondeterminism

First we consider theories given by the following operation and some of the following equations:

1 + 1 (c) (1 + 1)+ 1^1+ (1 + 1) i+t 1 + 1 (d) 1 + 1-^i-1 + 1 (e) 1 + 1

lch ch+4 h lch \ich 1 1 + 1-cCh-^ 1 1 1

A model of each such theory is given by a set A carrying the following function and satisfying the correct equations from among the following:

A x A (c) (A x A) x A-^A x (A x A) ^^ A x A (d) A x AA x A (e) A^^ A x A

lch chx4 „ lch

A A x A---^A A A

We see that models of these theories are exactly what we expect: without any equations we get magmas, with (c) semigroups, with (c), (d) commutative semigroups, with (c), (d), (e) semilattices, with (d) alone commutative magmas.

The corresponding monads are those of binary leaf trees (free magmas, T X = fiZ.X + Z x Z), nonempty lists (free semigroups), nonempty finite multisets (free commutative semigroups), nonempty finite sets (free semilattices), binary unordered leaf trees (free commutative magmas). All of them are quotients of the first monad. They all model nondeterminism to some level of granularity; which monad to use depends on what exactly one wants to track as the nondeterminism effect (and in fact on whether one wants to be able to resolve nondeterminism, as we will see shortly). The theory view of these monads tells us that the single operation ch is complete for programming finitely nondeterministic functions.

A comodel (a runner for nondeterministic computations) is a set C with the following function satisfying the intended equations from among the following:

c + c (c) (C + C) + c^—c + (C + C)C+Chc + c (d) c + c + c (e) c + c

\ch Ch+C| _ t^h fch

C C + C^-cCh-C Ch C C

Reformulating minimally, a comodel is a set C with a function ch = {chn, chs) : C ^ C x 2 satisfying the appropriate equations. For the theory without equations, it is nothing but a resolver (scheduler) for the finest notion of nondeterminism that remembers the order that binary choices are made, the order of options in binary choices etc. It is a machine that can make a binary choice on request and go to a new state. Given a nondeterministic computation, which is binary leaf-labelled tree in this case, it can thus choose a path from the root to some leaf.

Equation (e) forces that chn x = x. Equation (c) requires chs (chn x) = chs x and chn (chn x) = chn x, which are trivially fulfilled when chn is identity. So a resolver for the version of nondeterminism where order of binary choices is considered irrelevant and a binary choice between two equal options is considered the same as no choice at all (so computations are nonempty square-free lists of values, i.e., lists

with no sublist occurring twice in a row) amounts to a set C with an unconstrained function chs : C ^ 2, This is a machine that always makes its choice without changing its state, so, given a leaf tree (identified with other leaf trees that flatten into the same nonempty list), it walks down from the root by always turning to the left or always turning to the right, eventually reaching the leftmost or rightmost leaf (the first or last position of the list). Note that the other leaves (inner positions of the list) are unreachable for a runner—they are not addressable "crisply" enough.5

In a comodel for any theory containing equation (d), it must be that not (chs x) = chs x, which can only hold when C = 0. This says that, as soon as the order of the options in a choice is considered immaterial, resolving nondeterminism is impossible, apart from the uninteresting degenerate case.

The comonad for the equationless theory is that of streams of states and bits, D X = vZ.X x (2 x Z). The comonads for more specific theories are subcomonads. In particular, the comonad for the theory with (c) alone has DX = X x (2 x X), the theory with both (c) and (e) has DX = X x 2. The comonads for theories containing (d) have DX = 0.

Finite nondeterminism with failure

Let us consider extending the theories considered with the following operation and, possibly, the following equations:

0 (a) 0 + 1 (b) 1 + 0 i+nS 1 + 1

|die die+4 lCH

1 1 + 1-^ 1

A model is now a set A supporting the following function satisfying the intended equations from among following:

1 (a) 1 x A (b) A x x A

^die die X A^

dieX.A\ \ \ Ich

A axA-^ A A

Models are pointed magmas, monoids, commutative semilattices with a bottom, commutative pointed magmas. The monads are the monad of nullary-binary leaf trees (free pointed magmas, T X = ¡iZ.X + 1 + Z x Z) and its different quotients— the monads of lists (free monoids), finite multisets (free commutative monoids), finite sets (free commutative semilattices with bottom), nullary-binary unordered leaf trees (free pointed commutative magmas). They all model notions of nondeter-minism where also "no-option" choices are allowed.

A comodel is a set C with the following function satisfying the intended ones of

5 These two elements of T 3 are equal: to = ch (ch (var 0, var 1), var 2) and ti = ch (var 0, ch (var 1, var 2)). But to = /J-t'o and ti = n t'j for t0 = ch (var(ch (var 0, var 1)), var (var 2)) and t\ = ch (var (var 0), var (ch (var 1, var 2))) in T (T 3). Both t'0 and ti are of the form ch (var(...), var (...)). A runner that is able to extract from to the value 1, must process t' by first going to the left, but then it must do the same to ti in which case it cannot extract the value 1 from ti, which was equal to to.

the following equations:

(a) o + c

de + C|

(b) c-

C + dze

-0c+—C -

It is immediate that there are no interesting comodels: the carrier of a comodel must be empty even in the case of no equations. The comonads are all constant 0 (DX = 0). It is impossible (except for the uninteresting degenerate case of an impossible initial state) to resolve a nondeterministic computation that may fail.

Observe that the same happens with any theory with one or more nullary operations (op : 0 ^ O where O = 0) or, in terms of monads, with any monad such that T 0 = 0.

Partiality

Finally we could also skip OH and consider the theory with just die and no equations.

Models of this theory are pointed sets. The monad is the maybe monad (of sets with an added point, free pointed sets, TX = 1 + X), commonly used for modelling partiality. We learn the unsurprising fact that die is the sole operation needed for programming partial functions. We know already that there are no interesting comodels.

4-2 Interactive input/output

We move on to consider examples of other types. For the start, take two sets I, O, and consider the very simple theory with the following two operations and no equations:

|get j,PUT

A model is a set A endowed with functions

A ^ I A \get \put

A A ^ O

The monad is the free monad defined by T X = ¡j,Z.X + (Z ^ I) + O x Z. We recognize in it the monad for interactive input/output with I and O as the input and output alphabets.

A comodel is a set C with two functions

C x I C

^get |put

C C x O

It is a runner for interactive input/output, a machine that can provide input and consume output, changing its state. The comonad is the cofree comonad defined by DX = vZ.X x (Z x I) x (O ^ Z).

The case of interactive input only is covered by the special case O = 0 when we could just as well drop the operation put as forced and void of information.

Allowing interactive output only corresponds to dropping the get operation. This is different from the case I = 0 (input from an empty alphabet, leads to partiality), as well as from the case I = 1 (input from a singleton alphabet). But via P = O* (the free monoid on O) it is an instance of writing considered in the next section.

4-3 Stateful computation

We proceed to stateful computation. We first look at reading only and writing only, to then continue with reading and overwriting (modelled by state monads). We finish by analyzing reading and general updating (modelled by what we call update monads).

Reading

We begin with reading. Take a set S (of states). We look at this theory:

S U • > S SxS-A-S

|lkp |lkp lkpx4

1 1 1 xS-

A model is a set A with

A ^ S A ^ 1 A ^ S A ^ S x S-^^-A ^ S

hkp Up I \ikP

A -A (A ^ S) ^ S^^A ^ S^^-A

By the general construction, the monad for this theory is given by TX To X/^*x with To X and ^x defined inductively by

x : x f : To X ^ S

var x : To X Ikp f : To X

(so that To X = fZ. X + (Z ^ S)) and

ys.fs ^x f' s _ _

Ikp f ^x Ikp f' c ^x Ikp (Xs.c) Ikp (As'. Ikp (Xs.fss')) ~x Ikp (Xs.fss)

It is easy to verify that every element of T X can be presented in the normal form Ikp (As. var (f s)) for a unique f : X ^ S. It follows that the monad can alternatively be defined without quotienting by TX = X ^ S and nx = As.x, ¡if = As.fss. This is the reader monad for S as the state set. A comodel is a set C with

C x ! C x A

C x S C x 1 ^-- C x S C x (S x S) ^-C x S

^Ikp i hkp

^ ^^ ^ ' Ikp X S Ikp I

C C (C x S) x S ^-C x S ^—--C

or equivalently with

■ C C,

J Ikpn Ikpn

C C cJ^ C

¿kps j*

In the latter description, the 1st equation explicitly asks that Ikpn = idc, making Ikpn redundant, and the 2nd and 3rd follow, so we are left with a function Ikps : C ^ S and no equations. A runner for reading amounts thus to a machine that is happy to serve a lookup request with an external state (drawn from set S) and continue then in the same internal state (from set C)—so next time it will provide the same external state again.

It follows that the comonad can be defined by D X = X x S and e (x, s) = x, 5 (x, s) = ((x, s),s). This is the cofree comonad on the constant S functor.

Writing

For writing, we take a monoid (P, o, ©) (of updates) and consider the following theory:

1 i UPD> p i_UPD_^ p

jo UPD

UPD X P '

: 1 X P-^ P X P

A model of this theory is a set A with

A updj

-^A ^ P

A ^ 1 A ^ P (A ^ P) ^ P-^A ^ P x P

or, alternatively, in uncurried form,

P x A 1 x A

P x A (P x P) x A \Upd \

P upd upd

A P x (P x A)-P x A--—^ A

which is exactly what it means to be a left action of (P, o, ©).

The general construction tells us that the corresponding monad is given by TX = T0 X/ where To X and ~x are defined inductively by

p : P c : T0 X

var x : To X upd (p,c): To X

(so that ToX = iiZ.X + P x Z) and

c ^ X c

upd (p, c) ^x upd (p, c') c ^x upd (o, c) upd (p, upd (p',c)) ^x upd(p © p',c)

We can witness that every element of TX can be cast in the form upd (p, var x) for a unique pair (p, x) : P x X. As a consequence, the monad is alternatively definable

by TX = P x X and nx = (o,x), i (p, (p',x)) = (p © p',x). This is the familiar writer monad for (P, o, ©) as the monoid of updates.

A comodel for the theory of writing (a runner for writing computations) is a set C with

C^-—C x P

|cxo Upd^

upd X P

C x P-(C x P) x P-

C x (P x P)

i.e., a right action of the monoid. We think of it as a machine that listens to updates and changes its state.

The comonad is constructed by taking D X = D0 X | okx where D0 X and okx are defined coinductively by

c : D0 x c : D0 x p : P var c : x upd (c,p) : Do x

(so that D0 X = vZ.X x (P ^ Z)) and

ok x c

okx (upd (c,p)) c = upd (c, o) upd (upd (c,p),p') = upd (c,p © p')

Here it is the case that everything that can be learned at all about an element [ ] of D X (i.e., an ok element of D0 X) is summarized in the function Ap. var (upd ([ ],p)) : P ^ X. It is a universal way of observing elements of DX in the sense that, for any set Y, any function f : D X ^ Y is expressible as Ac. g (Ap. var (upd (c,p))) for a unique g : (P ^ X) ^ Y. Therefore, the comonad is more succinctly (without carving a subset) defined by D X = P ^ X, ev = v o, 5v = Ap. Ap'. v (p © p').

Reading and overwriting

We can now proceed reading and overwriting a state.

Given a set S (of states), the theory of reading and overwriting is given by two operations lkp and upd

|LKP jUPD

LKP UPD

lsnd I

UPD X S

-1x S-^SxS 1x S-

A model is a set A with functions lkp and upd such that

A ^ S A \lkp \upd

A A 4= S

A* > A <= S

\lkp upd|

A A ^ S——(A ^ S) ^ S-

^A^snd

-A ^ S x S

A ^ S-

upd^s|

(A ^ S) ^ S-

-A-—-^-A <= S

| A^A -A ^ S x S

T. Uustalu /Electronic Notes in Theoretical Computer Science 319 (2015) 403-421 or, alternatively, in uncurried form,

A ^ S S x A (S x A) ^ S A ^ S (S x S) x A-sndxA-S x A

\lkp \upd

\lkp \

, S x upd upd

-A S x (S x A)-S x A——

S x (A ^ S)-

Ax(A^S)| (S x S) x (A ^ S)-

S X Ikp

■S x (S x (A ^ S))-

The corresponding monad is T X = T0 X/^X where T0 X and ^x are defined inductively by

X : X f : To X ^ S s : S c : To X var x : T0 X Ikp f : T0 X upd (s,c): T0 X

(so that T0 X = fZ.X + (Z ^ S) + S x Z) and

c —X c

Vs.fs -X f' s _

Ikp f —x lkp f' upd (s,c) —x upd (s,c')

c ^x Ikp (As. upd (s, c)) upd (s, upd (s', c)) ~x upd (s',c) upd (s, Ikp f) ~x upd (s, f s)

As every element of TX can be uniquely presented in the normal form lkp (As. upd (gs, var (hs)) for some {g,h) : (S x X) ^ S, we have that TX = (S x X) ^ S whereby nx = As. (s, x), ff = As. let (s', g) — f s in g s' —the state monad for S.

A comodel is a set C together with functions lkp and upd such that

Cx S C flkp \updd C C x S

C^—C x S

|lkp updI

upd X S

C x S-(C x S) x S-

-C x S

jcxsnd

-C x (S x S)

lupd X S

(C x S) x S-

iCxA C x (S x S)

or, splitting lkp = {lkpn, Ikps)

^wn jlp j-

C C*^ C x S

I Ikps J upd

C C x S

\ {lkpn,lkps) upd

C C x S^p^ (C x S) x S'

-C x S

jcxsnd

C x (S x S)

lkpn upd lkps upd

C—C^-—C x S S< C^-—C x S

Here the 1st and 3rd equation together give that lkpn = idc making lkpn redundant. The 1st equation then simplifies to upd o {idc, lkps) = idc and the 3rd equation becomes tautological. We see that a runner for a stateful computation is a machine

responding to lookups (without changing its state) and listening to overwrites.6 This structure is known in bidirectional transformations [4] as a lens 7 between C and 5.8

The comonad is D X = D0 X | okx where D0 X and okx are defined coinduc-tively by

c : Do X c : Do X c : Do X s : S var c : X Ikpsc : S upd (c, s) : Do X

(so that Do X = vZ.X x S x (S ^ Z)) and

ok x c

ok x c

ok x c

ok x c

okx (upd (c,s)) c = upd (c, Ikpsc) upd (upd (c,s),s') = upd (c,s') Ikps (upd (c,s)) = s

All that can be known about an element [ ] of DX can be summarized in the universal observation (Ikps [ ], As. var (upd ([ ], s)) : S x(S ^ X). Hence the comonad can also be defined by DX = S x (S ^ X) and e (s,v) = vs and 5 (s,v) = (s,As'. (s',v)). This comonad is known as the costate (or array) comonad [13,9].

Reading and general writing

Let us also consider reading and general writing (as opposed to just overwriting) in combination.

Given a set S (of states), a monoid (P, o, ©) (of updates) and a right action 4 : S x P ^ S (describing application of updates to states), we are interested in the theory given by the following operations and equations:9

S 1 • > S S x S-

|lkp |lkp LKPXsj

1 1 1x S-

UPD, ,

_ UPD XP _ ' _

■ 1 X P-P P X P

' UPDXS

1 x S-^ P x S-

|lkp X P

A model a set A with functions Ikp and upd such that

A 4= S A 4= 1 \ikp A

A 4 S A 4 S x S

-S ^ A

Ikp^S Ikp '

(A 4 S) 4 S > A 4 S--—A

6 The computation has S as its state set; the runner's state set is C. The final comodel has C = S, lkps = ids and upd = snd, but it is not the only comodel. It is the case however that, for any comodel, C = S x C' for some set C'. The C' projection of the runner's state cannot be looked up, cannot be overwritten by computations.

7 More precisely, the bidirectional transformations term would be 'very well-behaved lens', but from our perspective the weaker (less well behaved) structures do not deserve the name 'lens'.

8 In that context, S is called the view state set and C the source state set.

9 This is not the minimal presentation, but the simplest one. The minimal one has the same operations, but three (more involved) equations.

1 UpD ^ P

A \upd

A* > A <= P

|A^0 upd|

A ^ 1 A ^ P upd^p (A ^ P) ^ P-

A ^ P -A ^ P x P

A ^ S-

(A ^ P) ^ S-

-A ^ P

Jlkp^P

A^(snd,^) I -A ^ P x S > A ^ S x P-(A ^ S) ^ P

where upd and the equations involving it can also be written in uncurried form. The monad is T X = T0 X/^X where T0 X and ^x are defined inductively by

f : To X ^ S p : P c : To X

var x : T0 X Ikp f : T0 X upd (p,c): T0 X

(so that To X = IJ,Z.X + (Z ^ S) + P x Z) and

c — X c

Vs.fs —X f' s _

Ikp f —x Ikp f' upd (p,c) —x upd (p,c') c —x Ikp (Xs.c) Ikp (As'. Ikp (Xs.fss')) —x Ikp (Xs.fss)

c ^x upd (o, c) upd (p, upd (p',c)) ~x upd (p © p',c) upd (p, Ikp f) ~x Ikp (As. upd (p, f (s i p)))

Since the equations allow us to present any element of T X uniquely in the normal form Ikp (As. upd (g s, var (h s))) for some {g, h) : (P x X) ^ S, we get that TX = (P x X) ^ S whereby

nx x = As. (o, x) VX f = As. Iet (p,g) ^ fs; (p',x) ^ g (s i p) in (p © p',x)

We have called this monad the update monad for S, (P, o, ©), | [2]. Update monads are exactly the compatible compositions of reader and writer monads—distributive laws between them are in bijections with right actions.

A comodel is a set C with functions lkp and upd such that

C x S C x 1-C

S x C C x (S x S)

tap f _

• I Ikp

c (C x S) x S C x S'

Cx S jlkp

C^-—C x p

jcxo updj"

Cx 1 lkp

upd x P

C x P -(C x P) x P-

lupd x S

(C x P) x S'

(snd,l)

-C x (P x S) < C x (S x P) -

cxej C x (P x P)

^TkpxP (C x S) x P

Splitting lkp = {lkpn, lkps), we see that the 1st equation just says lkpn = idc, making lkpn redundant. This makes the 2nd equation tautological and simplifies the 5th to

lkps upd

S < C —C x P

| lkps x P

---SxP

We have previously christened these structures update lenses [1], they are a refinement of state-based lenses. An update lens is a machine that responds to lookups (without changing its state) and listens to updates.

The corresponding comonad is D X = D0 X | okx where D0 X and okx are defined coinductively by

c : D0 X c : Do X c : Do X p : P

varc : X Ikpsc : S upd (c,p) : Do X

(so that D0 X = vZ.X x S x (P ^ Z)) and

ok x c ok x c ok x c ok x c

okx (upd (c,p)) c = upd (c, o) upd (upd (c,p),p') = upd (c,p © p') Ikps (upd (c,p)) = Ikps c X p

All information available about an element [ ] of D X is captured in the universal observation (Ikps [ ],Xp. var (upd ([ ],p))) : S x (P ^ X), which tells us that D X = S x (P ^ X) (the coupdate comonad) whereby

Ex (s, v) = v o &X (s,v) = (s,\p. (s X p,v (p © p')))

4-4 Continuations

Continuation monads have no rank, so our analysis in terms of Lawvere theories does not apply. However it it is easy to check directly that they cannot have non-trivial runners (i.e., runners with a non-empty carrier).

Indeed, fix a nonempty set R. A runner structure on a set C would be a monad morphism between the continuation monad for R and the state monad for C, so a family of maps Q : NX. (R ^ X) ^ R (C x X) ^ C. Consider 9q. The set (0 ^ R) ^ R is obviously inhabited (for any element r of R, it contains Xf. r), but for the set (C x 0) ^ C to be inhabited we need a function C — 0, which can only exist if C = 0.

5 Running vs. handling

Runners bear some similarity to Plotkin and Pretnar's handlers [12], but they are not the same. Let us spell out the exact relationship.

Broadly speaking, both are about specifying ways to extract a value from a computation.

Handling is based on the fact that, for any set A, (T A, fiA : T (T A) — T A) is the free (T, n, f)-algebra on A, with nA : A — T A as the associated injection.

Spelled out, this means that, given two sets A, B, a map f : A — B and a (T, n, f)-algebra structure g : T B — B, we have a unique map h : T A — B making the diagrams

A^ > TA< T (TA) \Th

—--TB

commute.

Running, at the same time, is based on the observation that any coalgebra (C, g : C ^ DC) of a suitable comonad (D, s, 5) induces a unique monad morphism between the given monad (T, n, f) and the state monad (TC, nC, fC). This is to say that we have a unique natural transformation O satisfying

X—TX^-—-T (TX)

^^ c . \T°X

TC XTc (Tc X)^^ T (Tc X)

The important differences are these. First, handlers are monomorphic and any codomain is possible: a handler defines map from T A to B for some fixed sets A, B. Runners are polymorphic, but the codomain is restricted to a specific form: a runner gives a family of functions from T X to TC X for a fixed set C. Second, the data inducing handlers and runners are different.

Runners are an instance of handlers, but not in a very useful way: as a circular unique existence property rather than a direct one. Indeed, in the diagram above we have rendered the pentagon stating the condition that Ox sends fx to fX in a layout suggesting that the composite map £x = fX ◦ Otcx might be a (T, n, f )-algebra structure on TC X, and it is easily verified to be so. But £x is defined in terms of Otc x, i.e., another component of O. So we cannot say that the algebra morphism Ox is induced by an independently given algebra structure £x .

Modulo this reservation, due to their polymorphic nature, runners are actually more than just handlers, they are uniform handlers. A general definition of a uniform handler proceeds from natural transformations as monad algebra structures. Say that a set functor F with a natural transformation a : T ■ F ^ F is a (T, n, f )-algebra (or a left module), if it also meets the conditions

t(T(fx))Tax > T(FX) ^Fxj aXI

T (FX ^^^ FX T (FX) ——-^ FX

It is now easy to check that the free (T, n, f )-algebra on F is (T ■ F, f ■ F : T ■ T ■ F ^ T ■ F), with n ■ F : F ^ T ■ F as the associating injection. Accordingly, for any functor G, a natural transformation ^ : F ^ G and a (T, n, f )-algebra structure ^ : T ■ G ^ G, we have a unique natural transformation % : T ■ F ^ G such that

FX nFX T (FX) < ^FX T (T (FX))

^ iXX ,X JTXX

GX^-iX— T (GX)

A runner O is now a uniform handler for F = Id, G = TC, $ = nC, ^ = fC ◦ (O ■ TC).

All of these considerations apply of course to any monad morphism from (T, n,f), e.g., the morphism to the continuation monad on the the carrier of a (T, n, f )-algebra discussed in Section 3—a monad morphism is always a monad algebra morphism.

420 T. Uustalu /Electronic Notes in Theoretical Computer Science 319 (2015) 403-421

6 Conclusion and future work

We showed when a computation in a given monad can be mapped into a stateful computation: it is when the state set carries a comodel of the corresponding Lawvere theory (a coalgebra of a suitable comonad). We find this to be a nice small new application of comodels (cf. the discussion by Behrisch et al. [3] on whether comodels are the "correct" dual of models). We also believe that it gives some new insight into the mechanics of different monadic/algebraic notions of effects, especially in regard to the impact the degree of abstractness (i.e., how much detail of effects we want to observe). For nondeterminism, for example, we saw that some approaches that make perfect sense for denotational semantics are not operational at all and there are simple mathematical reasons why this has to be so. We find it curious that state monads turn out to have a special role in connecting models and and comodels. Something similar appears in M0gelberg and Staton's work [7] on every monad being a linear state monad (under a certain viewpoint).

In future work, we intend to study sufficient conditions for a monad morphism to a state monad to be mono (so the stateful computation can capture all information in a given computation). We also plan to consider other target monads, in particular, combinations of state monads with other monads such as exception monads, and to relate this work and Plotkin and Power's [11] tensor of a comodel and a model.

Acknowledgment

I am most grateful to Gordon Plotkin, Alex Simpson, Tom Schrijvers and Nicolas Wu for the comments they made in response to my talks on this material as well as to the MFPS reviewers for their feedback. This research was supported by the ERDF funded projects EXCS and Coinduction, the Estonian Ministry of Education and Research institutional research grant no. IUT33-13 and the Estonian Science Foundation grant no. 9475.

References

[1] Ahman, D. and T. Uustalu, Coalgebraic update lenses, in: B. Jacobs, A. Silva, and S. Staton, eds., "Proc. of 30th Conf. on Mathematical Foundations of Programming Semantics, MFPS XXX (Ithaca, NY, June 2014)," Electron. Notes in Theor. Comput. Sci. 308, Elsevier, 2014, pp. 25-48.

[2] Ahman, D. and T. Uustalu, Update monads: cointerpreting directed containers, in: R. Matthes and A. Schubert, eds., "Proc. of 19th Conf.d on Types for Proofs and Programs, TYPES 2013 (Toulouse, Apr. 2013)," Leibniz Int. Proc. in Inform. 26, Dagstuhl Publishing, 2014, pp. 1-23.

[3] Behrisch, M., S. Kerkhoff, and J. Power, Category theoretic understandings of universal algebra and its dual: monads and Lawvere theories, comonads and what?, in: U. Berger and M. Mislove, eds., "Proc. of 28th Conf. on Mathematical Foundations of Programming Semantics, MFPS XXVIII (Bath, June 2012)," Electron. Notes in Theor. Comput. Sci. 286, Elsevier, 2012, pp. 5-16.

[4] Foster, J. N., M. B. Greenwald, J. T. Moore, B. C. Pierce, and A. Schmitt, Combinators for bidirectional tree transformations: a linguistic approach to the view-update problem, ACM Trans. on Program. Lang. and Syst. 29(3), 2007, article 17.

[5] Hyland, M., P. B. Levy, G. Plotkin, and J. Power, Combining algebraic effects with continuations, Theor. Comput. Sci. 375(1-3), 2007, pp. 20-40.

[6] Hyland, M. and J. Power, The category theoretic understanding of universal algebra: Lawvere theories and monads, in: L. Cardelli, M. Fiore, and G. Winskel, eds., "Computation, Meaning, and Logic: Articles Dedicated to Gordon Plotkin," Electron. Notes in Theor. Comput. Sci. 172, Elsevier, 2007, pp. 437-458.

[7] M0gelberg, R. E. and S. Staton, Linear usage of state, Log. Methods in Comput. Sci. 10(1), 2014, article 17.

[8] Moggi, E., Notions of computation and monads, Inf. and Comput. 93(1), 1991, pp. 55-92.

[9] O'Connor, R., Functor is to lens as applicative is to biplate: introducing multiplate, arXiv preprint 1103.2841, 2011. (Paper presented at WGP 2011, Tokyo, Sept. 2011.)

[10] Plotkin, G. and J. Power, Notions of computation determine monads, in: M. Nielsen and U. Engberg, "Proc. of 5th Int. Conf. on Foundations of Software Science and Computation Structures, FoSSaCS 2002 (Grenoble, Apr. 2002)," Lect. Notes in Comput. Sci. 2303, Springer, 2002, pp. 342-356. Springer (2002)

[11] Plotkin, G. and J. Power, Tensors of comodels and models for operational semantics, in: A. Bauer and M. Mislove, eds., "Proc. of 30th Conf. on Mathematical Foundations of Programming Semantics, MFPS XXIV (Philadelphia, PA, May 2008)," Electron. Notes in Theor. Comput. Sci. 218, Elsevier, 2008, pp. 295-311.

[12] Plotkin, G. and M. Pretnar, Handling algebraic effects, Log. Methods in Comput. Sci. 9(4), 2013, article

[13] Power, J. and O. Shkaravska, From models to comodels: state and arrays, in: J. Adamek and S. Milius, eds., "Proc. of 7th Int. Wksh. on Coalgebraic Methods in Computer Science, CMCS 2004 (Barcelona, March 2004)," Electron. Notes in Theor. Comput. Sci. 106, Elsevier, 2004, pp. 297-314.