Profunctor Optics: a Categorical Update

Optics are bidirectional data accessors that capture data transformation patterns such as accessing subfields or iterating over containers. Profunctor optics are a particular choice of representation supporting modularity, meaning that we can construct accessors for complex structures by combining simpler ones. Profunctor optics have previously been studied only in an unenriched and non-mixed setting, in which both directions of access are modelled in Set . However, functional programming languages are arguably better described by enriched categories; and we have found that some structures in the literature are actually mixed optics, with access directions modelled in different categories. Our work generalizes a classic result by Pastro and Street on Tambara theory and uses it to describe mixed V -enriched profunctor optics and to endow them with V -category structure. We provide some original families of optics and derivations, including an elementary one for traversals . Finally, we discuss a Haskell implementation.


Optics
Optics are an abstract representation of some common patterns in bidirectional data accessing.The most widely known optics are lenses, 'focusing' on a subfield A of a larger data structure S through a pair of functions view (S → A) and update (S × A → S) that respectively retrieve and modify the field.Lenses have been used in functional programming as a compositional solution to the problem of accessing fields of nested data structures [10] (Figure 1)., town ' = " London " , country ' = " UK " } >>> viewStreet example " 221 b Baker Street " >>> updateStreet example " 4 Marylebone Road " Address { street ' = " 4 Marylebone Road " , town ' = " London " , country ' = " UK " } Figure 1: Lenses are pairs of 'view' and 'update' functions that capture the repeating pattern of accessing subfields.Here, viewStreet extracts a field from a record, and updateStreet updates that field.
As the understanding of these data accessors grew, different families of optics were introduced for a variety of different types (e.g.prisms for disjoint unions and traversals for containers), each one of them capturing a particular data accessing pattern (Figure 2).

Modularity
It is straightforward to compose two lenses, one given by S → A and S × A → S and the other given by A → X and A × X → A, in order to access nested subfields.However, explicitly writing down this composition (or explaining it to a computer) can be tedious.Intercomposability only becomes increasingly difficult as other data accessors enter the stage: composing a lens given by S → A and S × A → S with a prism given by A → X + A and X → A can produce a function S → X × (X → S) + S, which is neither a lens nor a prism but a different optic known as affine traversal.Implementing explicitly a composition like this for every possible pair of optics would be prone to errors and result in a large codebase.However, we would like optics to behave modularly; in the sense that, given two optics, it should be possible to join them into a composite optic that directly accesses the innermost subfield., town ' = " London " , country ' = " UK " }) Figure 2: A prism is given by a pair of functions match and build that account for the possiblity of failure on pattern matching.In the figure, we verify whether a string can be parsed as an address.The combinator (?.) returns the results using the Maybe monad (see §6.Perhaps surprisingly, many implementations allow the programmer to wrap optics into a different representation and then use ordinary function composition to construct composite optics. How is it possible to compose two constructs that are not functions using ordinary function composition?Implementations provided by popular libraries such as lens [20], mezzolens [27] in Haskell, or profunctor-optics [12] in Purescript, achieve this effect by using different representations of optics in terms of polymorphic functions and the Yoneda lemma.This paper focuses on the encoding known as profunctor representation, which is based on the isomorphism between lenses (and optics in general) and functions that are polymorphic over profunctors with a particular algebraic structure called a Tambara module.Optics under this encoding are called profunctor optics.

Profunctor optics
Profunctor optics, and various other representations of lenses, were originally proposed in functional programming as a compositional solution to the problem of accessing fields of nested data structures [10,41].
Different families of profunctor optics are intercomposable.When we use the profunctor representation of optics, composing optics of different kinds becomes also a particular case of polymorphic function composition.Together, all families of optics form a powerful language for modular data access.Consider the example of Figure 3, where a lens and a prism are used in conjunction to manipulate parts of a string.
Moreover, optics can be used to entirely change not only the value but the type of the focus, and propagate that change back to the original data structure.These are called type-variant optics, in contrast with the type-invariant optics we have introduced so far (Figure 4).In that case, the functions defining the optic need to account for that type change (commonly, by also introducing polymorphism), but the internal representation will work the same.The optics we discuss in this paper are assumed to be type-variant, with type-invariant optics being a special case.In its profunctor representation, each optic is written as a single function that is polymorphic over profunctors with a certain algebraic structure.For instance, lenses can be written as functions polymorphic over cartesian profunctors, whereas prisms can be written as functions polymorphic over cocartesian profunctors [31, §3].Milewski [25] identified these algebraic structures (cartesian profunctors, cocartesian profunctors, . . . ) as Tambara modules [40] and used a result by Pastro and Street [30] to propose a unified definition of optic.This definition has been later extended by Boisseau and Gibbons [3] and Riley [34], both using different techniques and proposing laws for optics.

Mixed profunctor optics
However, the original result by Pastro and Street cannot be used directly to unify all the optics that appear in practice.Our work generalizes this result, going beyond the previous definitions of optic to cover mixed [34, §6.1] and enriched optics.
The generalized profunctor representation theorem captures optics already present in the literature and makes it possible to upgrade them to more sophisticated definitions.For instance, many generalizations of lenses in functional programming are shown to be particular cases of a more refined definition that uses mixed optics (Definition 3.1).We also show derivations for some new optics that were not present in the literature (Definitions 3.8, 3.26 and 3.31).Finally, Milewski [25] posed the problem of fitting the three basic optics (lenses, prisms and traversals) into an elementary pattern; lenses and prisms had been covered in his work, but traversals were missing.We present a new description of traversals in terms of power series functors (Proposition 3.22) whose derivation is more direct than the ones based on traversables as studied by Jaskelioff and Rypacek [17].

Coend Calculus
Coend calculus is a branch of category theory that describes the behaviour of ends and coends, certain universal objects associated with profunctors P : C op × C → V. Ends can be thought of as some form of universal quantifier, whereas coends can be thought of as their existential counterparts.
Ends are subobjects of the product X∈C P (X, X), whereas coends result from quotienting the coproduct X∈C P (X, X).Both take into account the fact that P depends on two "terms", covariantly on the second, and contravariantly on the first.Definition 1.1 (Ends and coends).The end is the equalizer of the action of morphisms on both arguments of the profunctor, whereas the coend is dually defined as a coequalizer.end(P ) := eq X∈C P (X, X) f : A→B P (A, B) , Ends are usually denoted with a subscripted integral; coends use a superscripted integral.
In both cases, X is a dummy variable, and we consider X∈C P (X, X) and Y ∈C P (Y, Y ) 'equivalent modulo α-conversion'.The notation draws on an analogy with elementary calculus.An integral f (x) dx depends "covariantly" on the variable x defined, say, on R n , whereas the differential "dx" can be regarded as an element of the dual space (R n ) * .An even more striking analogy is that co/ends satisfy a form of 'Fubini rule' and a 'Dirac delta' integration rule (see Proposition 1.3 and Proposition 1.2).
Theorems involving ends and coends can be proved using their universal properties.Here, we offer a terse account of coend calculus [4,22].Using the calculus based on the following rules, it is possible to construct isomorphisms between objects of a category by means of a chain of 'deduction steps'.Proposition 1.2.Evaluation on the identity defines the following isomorphisms, called Yoneda and coYoneda reductions, respectively.
where ⊗ is the tensor product in the monoidal category V (the base of the enrichment for C) and F : C → V is a co-presheaf (there are analogous identities for presheaves).
Proposition 1.3.The Fubini rule is satisfied up to isomorphism.
Proposition 1.5.The set of natural transformations can be rewritten as a coend.
In particular, coend calculus expressions are commonly simplified using adjunctions (F ⊣ G): an adjunction is equivalently an isomorphism D(F X, Y ) ∼ = C(X, GY ).

Contributions
Our first contribution is the derivation and partial classification of mixed optics, covering both optics existing in the literature and some novel ones, all following a unified definition (Definition 2.1).
Our work completes and extends the classification of (non-mixed) optics in [3,34].Explicitly, we present a new family of optics in Definition 3.8, that unifies new examples with some optics already present in the literature, such as achromatic lenses [2, §5.2].We introduce an original derivation showing that monadic lenses [1] are mixed optics in Proposition 3.6.Similarly, in Proposition 3.4, we present a novel derivation showing that the appropiate generalization of lenses to an arbitrary monoidal category [38, §2.2] is not an optic but a mixed optic.We give a unified definition of lens in Definition 3.1, that for the first time can be specialized to all of these previous examples.Finally, we present a new derivation of the optic known as traversal in Proposition 3.22.
Our second contribution is the definition of the enriched category of mixed profunctor optics.The construction requires a generalization of the Tambara modules of [30] that had been used to define categories of profunctor optics [3,34] to generalized Tambara module.This is done in Section 4. As a corollary, we extend the result that justifies the use of the profunctor representation of optics in functional programming to the case of enriched and mixed optics (Theorem 4.14), endowing them with V-category structure.

Synopsis
We introduce the definition of mixed optic in Section 2. Section 3 describes some practical examples from functional programming and shows how they are captured by the definition.Section 4 describes how the theory of Tambara modules can be applied to obtain a profunctor representation for optics.Section 5 contains concluding remarks.The Appendix (Section 6) introduces the details of a full Haskell implementation.

Setting
We shall work with categories enriched over a Bénabou cosmos (V, ⊗, I); that is, a (small)-complete and cocomplete symmetric monoidal closed category.In particular, V is enriched over itself, and we write the internal hom-object between A, B ∈ Obj(V) as V(A, B).Our intention is to keep a close eye on the applications in functional programming: the enriching category V should be thought of as the category whose objects model the types of an idealized programming language and whose morphisms model the programs.Because of this, V will be cartesian in many of the examples.We can, however, remain agnostic as to which specific V we are addressing.
For calculations, we make significant use of coend calculus as described, for instance, by Loregian [22].The proofs in this paper can be carried out without assuming choice or excluded middle, but there is an important set-theoretical issue: in some of the examples, we compute coends over non-small categories.We implicitly fix a suitable Grothendieck universe and our categories are to be considered small with respect to that universe.As Riley [34, §2] notes, this will not be a problem in general: even if some coends are indexed by large categories and we cannot argue their existence using the cocompleteness of Set, we will still find them represented by objects in the category.

Optics
Our first goal is to give a unified definition that captures what it means to be an optic.We have seen so far how lenses and prisms work (Figures 1 and 2).A common pattern can be extracted from these two cases.Lenses can be constructed when we have a function that splits some data structure of type S into something of the form M × A and then recombines it back to S. Here, A is the type of the field we want to focus on, and M is the type combining the remaining fields that constitute S. From this split, we can extract the pair of functions C(S, A) × C(S × A, S) that define a lens.Prisms can be constructed when we have a function that can split some data structure of type S into something of the form M + A and put the pieces together again.
The structure that is common to all optics is that they split a bigger data structure of type S ∈ C into some focus of type A ∈ C and some context or residual M ∈ M around it.We cannot access the context directly, but we can still use its shape to update the original data structure, replacing the current focus by a new one.The definition will capture this fact imposing a quotient relation on the possible contexts; this quotient is expressed by the dinaturality condition of a coend.The category of contexts M will be monoidal, allowing us to compose optics with contexts M and N into an optic with context M ⊗ N .Finally, as we want to capture type-variant optics, we leave open the possibility of the new focus being of a different type B ∈ D, possibly in a different category, which yields a new data structure of type T ∈ D. This is summarized in Figure 5.The common structure of an optic.We could provide semantics for diagram of this kind in terms of profunctors, see [37].
Multiple definitions of optics of increasing generality have been given in [3,25,34].We encompass all of them under an abstract definition in terms of monoidal actions.
Let (M, ⊗, I, a, λ, ρ) be a monoidal V-category [6].Let it act on two arbitrary V- for the structure isomorphisms of the monoidal actions L and R , which we use in infix notation.Definition 2.1.Let S, A ∈ C and T, B ∈ D. An ( L , R )-optic from (S, T ) with the focus on (A, B) is a (generalized) element of the following object described as a coend: The two monoidal actions L and R represent the two different ways in which the context interacts with the focus: one when the data structure is decomposed and another one, possibly different, when it is reconstructed.By varying these two actions we will recover many examples from the literature and introduce some new ones, as the table in Figure 6 summarizes.

Name
Description Actions Base The purpose of an abstract unified definition is twofold: firstly, it provides a framework to classify existing optics and explore new ones, as we do in Section 3; and secondly, it enables a unified profunctor representation, which we present in Section 4.

Examples of optics 3.1 Lenses and prisms
Lenses can be seen as accessors for a particular subfield of a data structure.In its basic form, they are given by a pair of functions: the view function that accesses the subfield; and the update function that overwrites its contents.
The basic definition of lens [10,28,29] has been generalized in many different directions.Monadic lenses [1], lenses in a symmetric monoidal category [38, §2.2], linear lenses [34, §4.8] or achromatic lenses [2, §5.2] are some of them.These generalizations were not meant to be mutually compatible.They use the monoidal structure in different ways and introduce monadic effects in different parts of the signature.Some were not presented as optics, and a profunctor representation for them was not considered.We present a unified description that captures all of these variants.
We present two derivations of lenses as mixed optics that capture all of the variants mentioned before, together with new ones, and endow them with a unified profunctor representation (Theorem 4.14).
The first derivation is based on cartesian structure.It generalizes the original derivation [25] and captures lenses in a symmetric monoidal category (Definition 3.3) and monadic lenses (Definition 3.5).It is then refined to cover achromatic lenses and describe some new variants of optics missing in the literature.The second derivation slightly generalizes linear lenses [34, §4.8] and uses the closed structure instead.

Lenses
Most variants of lenses rely on a cartesian monoidal structure.Throughout this section, we take a cartesian closed category (W, ×, 1) as our base for enrichment.During the rest of the paper we will explicitly use W to refer to a cartesian monoidal base of enrichment and use V to refer to a notnecessarily-cartesian base of enrichment.A monoidal W-category (C, ×, 1) is said to be cartesian Proof.The universal property of the product can be summarized as it being right adjoint to the diagonal functor (∆) : This definition can be specialized to the pair C(S, A) × C(S × B, T ) if we take C = D and we let (•) be the cartesian product.It is, however, more general than that, and it captures the following examples (Definitions 3.3 and 3.5).Proof.The category of cocommutative comonoids CCom over a category C can be given a cartesian structure in such a way that the forgetful functor U : CCom → C is strict monoidal (Fox shows a stronger result [11]).By Proposition 3.2, we can show Proof.Every W-endofunctor is strong: this is because a functor F : W → W with a strength is the same thing as a W-enrichment of the functor [21].Thus, the W-monad Ψ comes with a W-natural family θ X,Y : X × Ψ(Y ) → Ψ(X × Y ).This induces a W-action (⋊) : W × Kl(Ψ) → Kl(Ψ), with Kl(Ψ) the Kleisli category of the monad; defined, on morphisms, as the composite

Algebraic lenses
We can further generalize Definition 3.1 if we allow the context over which we take the coend to be an algebra for a fixed monad.The motivation is that lenses with a context like this appear to have direct applications in programming; for instance, the achromatic lenses of [3] are a particular case of this definition.These algebraic lenses should not be confused with the previous monadic lenses in Definition 3.5.
Proof.The W-category of algebras is cartesian, making the forgetful functor Remark 3.10.Algebraic lenses are a new optic.When (•) is the cartesian product, algebraic lenses are given by the usual view function that accesses the subfield, and a variant of the update function that takes the original source as a computation rather than a value.
Example 3.11.The algebraic lens for the list monad L : V → V is a new kind of optic that we dub a classifying lens.This is given by two functions, the usual view function that accesses the focus, and a classify function that takes a list of examples together with some piece of data and produces a new example.A classifying lens can be trained with a dataset (Figure 8) to classify a new focus into a complete data structure.A learning algorithm (in this case, a naive version of nearest neighbor) defines an algebraic lens that can be used to classify foci into full data structures.It can be implemented by view and create functions, this time together with a maybeUpdate that is allowed to fail.

Lenses in a closed category
Linear lenses are a different generalization of lenses which relies on a closed monoidal structure.
Their advantage is that we do not need to require our enriching category to be cartesian anymore.

Prisms
Prisms pattern-match on data structures and handle a possible failure to match.They are given by a match function that tries to access the matched structure and a build function that constructs an abstract type from one of its possible matchings.Prisms happen to be lenses in the opposite category.However, they can also be described as optics in the original category for a different pair of actions.We will provide a derivation of prisms that is dual to our derivation of lenses for a cartesian structure.This derivation specializes to the pair C(S, T + A) × C(B, T ).The coalgebraic variant is given by a cMatch function, that captures the failure into a comonad, and the usual build function.

Traversals
Traversals extract the elements of a finitary container [27] into an ordered list, allowing us to iterate over the elements without altering the container (Figure 9).Remark 3.21.Let (N, +) be the free strict monoidal V-category on one object.Ends and coends indexed by N coincide with products and coproducts, respectively.Here A (−) : N → C is the unique monoidal V-functor sending the generator of N to A ∈ C. Each functor X : N → C induces a power series This defines an action Pw : [N, C] → [C, C] sending the indexed family to its power series (see Remark 3.23).We propose a derivation of the traversal as the optic for power series.Proof.The derivation generalizes that of linear lenses (Definition 3.14).
The derivation from the general definition of optic to the concrete description of lenses and prisms in functional programming was first described by [31] and [25], but finding a derivation of traversals like the one presented here, fitting the same elementary pattern as lenses or prisms, was left as an open problem.It should be noted, however, that derivations of the traversal as the optic for a certain kind of functor called Traversables (which should not be confused with traversals themselves) have been previously described by [3,34].For a derivation using Yoneda, [34] recalls a parameterised adjunction that has an equational proof in the work of [16].These two derivations do not contradict each other: two different classes of functors can generate the same optic; if, for instance, the adjunction describing both of them gives rise to the same monad.This seems to be the case here: traversables are coalgebras for a comonad and power series are the cofree coalgebras for the same comonad [36, §4.2].
In the Sets-based case, the relation between traversable functors, applicative functors [24] and these power series functors has been studied by [17].
We are then considering an implicit non-symmetric monoidal structure where the monoidal product ( This is precisely the structure described by Kelly [19, §8] for the study of non-symmetric operads. A similar monoidal structure is described there when we substitute N by (P, +), the V-category of permutations defined as the free strict symmetric monoidal category on one object.The same derivation can be repeated with this new structure to obtain an optic similar to the traversal, with the difference that elements are not ordered explicitly, and given by

Affine traversals
Affine traversals strictly generalize prisms and linear lenses in the non-mixed case allowing a lenslike accessing pattern to fail; they are used to give a concrete representation of the composition between a lens and a prism.An affine traversal is implemented by a single access function.Proof.The action uses that the monoidal product, which is in this case a left adjoint, distributes over the coproduct.

Kaleidoscopes
Applicative functors are commonly used in functional programming as they provide a convenient generalization to monads with better properties for composition; they form the V-category App of monoids with respect to Day convolution ( * ) : which is defined as Alternatively, they are lax monoidal V-functors for the cartesian structure.It is natural to ask what is the optic associated with applicative functors.We know from a basic result in category theory [23, §VII, Theorem 2] that, as the category [V, V] has coproducts indexed by the natural numbers, and Day convolution distributes over them, the free applicative functor can be computed as the colimit (I + F + F * 2 + F * 3 + . . .).Having characterized free applicative functors, computing their associated optic amounts to an application of coend calculus.Proof.Let U : App → [V, V] be the forgetful functor from the category of applicatives.
Remark 3.28.The free applicative we construct here is known in Haskell programming as the FunList applicative [42].In the same way that traversables are written in terms of lists, we can approximate Kaleidoscopes as a single function aggregate :: that takes a folding for the foci and outputs a folding for the complete data structure.Kaleidoscopes are a new optic, and we propose to use them as accessors for pointwise foldable data structures.
Kaleidoscopes pose a problem on the side of applications: they cannot be composed with lenses to produce new kaleidoscopes.This is because the constraint defining them (Applicative) is not a superclass of the constraint defining lenses: a functor given by a product is not applicative, in general.However, a functor given by a product by a monoid is applicative.This means that applicatives can be composed with lenses whose residual is a monoid, which are precisely the newly defined classifying lenses (Definition 3.8).

Grates
Grates create a new structure when provided with a way of creating a new focus from a view function.They are given by a single grate function with the form of a nested continuation.
The description of a grate and its profunctor representation in terms of "closed" profunctors was first reported by Deikun and O'Connor [26]; it can be seen as a consequence of the profunctor representation theorem (Theorem 4.14).

Glasses
Glasses are a new optic that strictly generalizes grates and lenses for the cartesian case.In functional programming, glasses can be implemented by a single function glass that takes a way of transforming views into new foci and uses it to update the data structure.We propose to use them as a concrete representation of the composition of lenses and grates.

Getters, reviews and folds
Some constructions, such as plain morphisms, can be regarded as degenerate cases of optics.We will describe these constructions (getters, reviews and folds [20]) as mixed optics.All of them set one of the two base categories to be the terminal category and, contrary to most optics, they act only unidirectionally.We will derive the usual implementations of getters as s -> a, of reviews as b -> t, and of folds as s -> [a].Their profunctor representation can be seen as a covariant or contravariant application of the Yoneda lemma.The category of foldable functors, Foldable, is the slice category on the list functor L : V → V, also known as the free monoid functor.Using the fact that L is a monad, the slice category [V, V]/L can be made monoidal in such a way that the forgetful functor [V, V]/L → [V, V] becomes monoidal.Definition 3.34.Folds are optics for the action of foldable functors and the trivial action on the contravariant side.

Fold((A, * ), (S, *
Folds admit a concrete description, V(S, LA), which can be reached from the definition of coends as colimits.A coend from a diagram category with a terminal object is determined by the value at the terminal object and here, L is the terminal object.The same technique can be used to prove that the optic for the slice category over a monad G : V → V has a concrete form given by C(S, GA).

Setters and adapters
We finish our examples of optics with two extremes: the actions from the initial and terminal actions.These are the identity action id : [V, V] → [V, V] and picking the monoidal unit, I :

Definition 3.35.
A setter [20] is an element of
Remark 3.37.In functional programming, we implicitly restrict to the case where V is a cartesian category, and we curry this description to obtain the usual representation of setters as a single over function.

Optics for (co)free
A common pattern that appears across many optic derivations is that of computing the optic associated with a class of functors using an adjunction to allow for an application of the Yoneda lemma.This observation can be generalized to a class of concrete optics.Consider some V-endofunctor H : V → V. Any objects A, B, S, T ∈ V can be regarded as functors from the unit V-category.The following isomorphisms are the consequence of the fact that left and right global Kan extensions are left and right adjoints to precomposition, respectively.

V(S, HA)
These extensions exist in V and they are given by the formulas Proof.We prove the first case.The second one is dual.

Tambara theory
A fundamental feature of optics is that they can be represented as a single polymorphic function.Optics in this form are called profunctor optics and we say this function is their profunctor representation.Profunctor optics can be easily composed, even if they are from different families: composition of optics as polymorphic functions becomes ordinary function composition.Figure 3 shows an example of this phenomenon.Profunctor optics are functions polymorphic over profunctors endowed with some extra algebraic structure.This extra structure depends on the family of the optic they represent.For instance, lenses are represented by functions polymorphic over cartesian profunctors, while prisms are represented by functions polymorphic over cocartesian profunctors [31, §3].Milewski [25] notes that the algebraic structures accompanying these profunctors are precisely Tambara modules, a particular kind of profunctor that has been used to characterize the monoidal centre of convolution monoidal categories [40].Because of this correspondence, categories of lenses or prisms can be obtained as particular cases of the "Doubles for monoidal categories" construction defined by Pastro and Street [30, §6].The double1 of an arbitrary monoidal V-category (A, ⊗, I), is a promonoidal2 V-category DA whose hom-objects are defined as

A(S, C ⊗ A) ⊗ A(C ⊗ B, T ).
In the particular case where A is cartesian or cocartesian, the V-category DA is precisely the category of lenses or prisms over A, respectively.Moreover, one of the main results of [30, Proposition 6.1] declares that the V-category [DC, V] of copresheaves over these V-categories is equivalent to the V-category of Tambara modules on C. In the case of lenses or prisms, these Tambara modules are precisely cartesian and cocartesian profunctors, and this correspondence justifies their profunctor representation.
We will see how the results of Pastro and Street can be directly applied to the theory of optics, although they are not general enough for our purposes.Milewski [25] already proposed a unified description of optics, later extended by [3] and [34], that requires a generalization of the original result by Pastro and Street from monoidal products to arbitrary monoidal actions.In order to capture V-enriched mixed optics, we need to go even further and generalize the definition of Tambara module in two directions.The monoidal category A in their definition needs to be substituted by a pair of arbitrary categories C and D, and the monoidal product ⊗ A : A ⊗ A → A needs to be substituted by a pair of arbitrary monoidal actions L : M⊗C → C and R : M⊗D → D, from a common monoidal category M.
This section can be seen both as a partial exposition of one of the main results of the work of Pastro and Street [30, Proposition 6.1] and a generalization of their definitions and propositions to the setting that is most useful for applications in functional programming.

Generalized Tambara modules
Originally, Tambara modules [40] were conceived of as a structure on top of certain profunctors that made them play nicely with some monoidal action in both their covariant and contravariant components.
For our purposes, Tambara modules represent the different ways in which we can use an optic.If a profunctor P has Tambara module structure for the monoidal actions defining an optic, we can use that optic to lift the profunctor applied to the foci, P (A, B), to the full structures, P (S, T ).For instance, the profunctor (−) × B → (−) can be used to lift the projection A × B → B into the update function S × B → T .In other words, this profunctor is a Tambara module compatible with all the families of optics that admit an update function, such as lenses.In programming libraries, that profunctor can be used to define a polymorphic update combinator that works across different families of optics.
Formally, we want to prove that Tambara modules for the actions L and R are copresheaves over the category Optic L , R .This will also justify the profunctor representation of optics in terms of Tambara modules (Theorem 4.14).
for every M, N ∈ M, every A ∈ C and every B ∈ D. Let us repeat the equations in terms of commutative diagrams for clarity.This is a family of morphisms making the following two diagrams commute.
When V = Set, we can define a morphism of Tambara modules as a natural transformation η A,B : For an arbitrary V, Tambara modules are the objects of a V-category Tamb whose hom-object from (P, α) to (Q, α ′ ) is computed as the equalizer of the arrows and Remark 4.2.Pastro and Street [30] follow the convention of omitting the unitors and the associators of the monoidal category when defining Tambara modules.These appear in Definition 4.1 replaced by the structure isomorphisms of the two monoidal actions.

Pastro-Street's "double" comonad
Tambara modules are coalgebras for a particular comonad [30, §5] in profunctors.That comonad has a left adjoint that must therefore be a monad, and then Tambara modules can be equivalently described as algebras for that monad.We will describe the V-category of generalized Tambara modules Tamb as an Eilenberg-Moore category first for a comonad and then for its left adjoint monad.This will be the main lemma (Lemma 4.6) towards the profunctor representation theorem (Theorem 4.14).
given by the composition of the actions ( L ) and ( R ) with the evaluation V-functor C op ⊗ D ⊗ Prof (C, D) → V. On objects, this is given by By the universal property of the end, this induces a V-functor Proposition 4.7.The Θ comonad has a left V-adjoint Φ, which must therefore be a monad.On objects, it is given by the following formula.
Proof.We can explicitly construct the V-natural isomorphism using coend calculus.
Alternatively, the adjunction can be deduced from the definition of the comonad Θ and the characterization of global Kan extensions as adjoints to precomposition.

Pastro-Street's "double" promonad
The second part of this proof occurs in the bicategory of V-profunctors.In this bicategory, there exists a formal analogue of the Kleisli construction that, when applied to the Pastro-Street monad Φ, yields a category whose morphisms are the optics from Definition 2.1.This is the crucial step of the proof, as the universal property of that Kleisli construction will imply that copresheaves over the category of optics there defined are Tambara modules (Lemma 4.10).After that, the last step will be a relatively straightforward application of the Yoneda lemma (Lemma 4.12).
Let Prof be the bicategory of V-profunctors that has as 0-cells the V-categories C, D, E, . ..; as 1-cells P : C ↛ D the V-profunctors given as P : C op ⊗ D → V; and as 2-cells the natural transformations between them.The composition of two V-profunctors P : There is, however, an equivalent way of defining profunctor composition if we interpret each V-profunctor C op ⊗ D → V as a V-functor C op → [D, V] to the category of copresheaves.In this case, the composition of two profunctors P : The unit profunctor for composition is precisely the Yoneda embedding.
In the same way that we can construct a Kleisli category over a monad, we will perform a Kleisli construction over the monoids of the bicategory Prof , which are called promonads.Promonads over the base category V that are also Tambara modules for the product appear frequently in the literature on functional programming languages under the name of arrows [14,15,35].

Definition 4.8.
A promonad is given by a V-category A, an endoprofunctor T : satisfying the following unitality and associativity axioms.
A module for the promonad is a V-profunctor P : X op ⊗ A → V, together with a V-natural transformation ρ : T ⋄ P → P making the following diagrams commute.
An algebra is a module structure on a V-copresheaf P : A → V, interpreted as a profunctor I op ⊗ A → V from the unit V-category.
Clarke, Elkins, Gibbons Profunctor Optics: a Categorical Update Lemma 4.9.The bicategory Prof admits the Kleisli construction [30, §6].The Kleisli V-category Kl(T ) for a promonad (T, µ, η) over A is constructed as having the same objects as A and letting the hom-object between X, Y ∈ A be precisely T (X, Y ) ∈ V.
Proof.The multiplication of the promonad is a V-natural transformation whose components can be taken as the definition for the composition of the V-category Kl(T ).The following isomorphism is a consequence of continuity.
Let us show now that this V-category satisfies the universal property of the Kleisli construction.Let P : X op ⊗ A → V be a V-profunctor.A module structure ρ : T ⋄ P → P corresponds to a way of making the profunctor P functorial over Kl(T ) in the second argument Functoriality of this family follows from the monad-algebra axioms.
Lemma 4.10.The category of algebras for a promonad is equivalent to the copresheaf category over its Kleisli object.
Proof.Let X be any category and Φ : Y → Y a promonad.By the universal property of the Kleisli construction (see Lemma 4.9), Prof (X, Kl(Φ)) is equivalent to the category of modules on X for the promonad.In particular, V-profunctors from the unit V-category to the Kleisli object form precisely the category EM(Φ) of algebras for the promonad; thus be a cocontinuous monad.The profunctor Ť : A op → [A, V] defined by Ť := T • y can be given a promonad structure.Moreover, algebras for T are precisely algebras for the promonad Ť .
Proof.First, the fact that T is cocontinuous means that it preserves left Kan extensions and thus, This means that the composition of the profunctor Ť with itself is As a consequence of this for the case P : I → [A op , V], any T -algebra can be seen as a Ť -algebra and vice versa.The axioms for the promonad structure on Ť coincide with the axioms for the corresponding monad on T .
In particular, the Pastro-Street monad Φ is a left adjoint.That implies that it is cocontinuous and, because of Proposition 4.11, it induces a promonad Φ = Φ • y, having Tambara modules as algebras.We can compute by the Yoneda lemma that This coincides with Definition 2.1.We now define Optic to be the Kleisli V-category for the promonad Φ.

Profunctor representation theorem
Let us zoom out to the big picture again.It has been observed that optics can be composed using their profunctor representation; that is, profunctor optics can be endowed with a natural categorical structure.On the other hand, we have generalized the double construction in [30] to abstractly obtain the category Optic.The final missing piece that makes both coincide is the profunctor representation theorem, which will justify the profunctor representation of optics and their composition in profunctor form being the usual function composition.
The profunctor representation theorem for the case V = Set and non-mixed optics has been discussed in [3,Theorem 4.2].Although our statement is more general and the proof technique is different, the main idea is the same.In both cases, the key insight is the following lemma, already described by [25].Lemma 4.12 ("Double Yoneda" from [25]).For any V-category A, the hom-object between X and Y is V-naturally isomorphic to the object of V-natural transformations between the functors that evaluate copresheaves in X and Y ; that is,

The isomorphism is given by the canonical maps
Its inverse is given by computing its value on the identity on the A(X, −) component.
Proof.In the functor V-category [A, V], we can apply the Yoneda embedding to two representable functors A(Y, −) and A(X, −) to get Here reducing by Yoneda lemma on both the left hand side and the two arguments of the right hand side, we get the desired result.Proof.We apply Double Yoneda (Lemma 4.12) to the V-category Optic and then use that copresheaves over it are precisely Tambara modules (Proposition 4.10).
The immediate practical application of this theorem is to justify the following profunctor representation forall p .Tambara p = > p a b -> p s t for all the optics we've been discussing in this paper, where the Tambara constraint is replaced by the class of profunctors preserving the appropriate monoidal action.For instance, the standard lens type Lens a b s t = forall p .Cartesian p = > p a b -> p s t is defined by the class of profunctors preserving the action defined by the cartesian product, which are Tambara modules for the cartesian product.A similar encoding works for the rest of the optics.

Conclusions
We have extended a result by Pastro and Street to a setting that is useful for optics in functional programming.Using it, we have refined some of the optics already present in the literature to mixed optics, providing derivations for each one of them.We have also described new optics.
Regarding functional programming, the work suggests an architecture for a library of optics that would benefit from these results.Instead of implementing each optic separately, the general definition can be instantiated in all the particular cases.We can then just consider specific functions for constructing the more common families of optics.Tambara modules can be used to implement each one of the combinators of the library, ensuring that they work for as many optics as possible.The interested reader can find the implementation in Appendix 6.
Many of the other applications of optics may benefit from the flexibility of enriched and mixed optics.They may be used to capture some lens-like constructions and provide a general theory of how they should be studied; the specifics remain as future work.

Van Laarhoven encoding
This paper has focused on the profunctor representation of optics.A similar representation that also provides the benefit of straightforward composition is the van Laarhoven encoding [41].It is arguably less flexible than the profunctor representation, being based on representable profunctors, but it is more common in practice.For instance, Proposition 5.1 (Van Laarhoven-style traversals).Traversals admit a different encoding in terms of profunctors represented by an applicative functor.
Proof.By coend calculus, using the Yoneda lemma.

Grate((A, B), (S, T
Proof.Again by coend calculus, and using the Yoneda lemma.

Related work
Pastro and Street [30] first described the construction of doubles in their study of Tambara theory.Their results can be reused for optics thanks to the observations of [25].The profunctor representation theorem and its implications for functional programming have been studied by [3].We combine their approach with Pastro and Street's to get a proof of a more general version of this theorem.
The case of mixed optics was first mentioned by Riley [34, §6.1], but his work targeted a more restricted case.Specifically, the definitions of optic given in the literature [3,25,34] deal only with the particular case in which V = Set, the categories C and D coincide, and the two actions are the same.Riley derives a class of optics and their laws [34, §4.4] that is closely related to ours in Section 3.6; our proposal makes stronger assumptions but may be more straightforward to apply in programming contexts.Riley uses the results of [16] to propose a description of the traversal in terms of traversable functors [34, §4.6]; our derivation simplifies this approach, which was in principle not suitable for the enriched case.
A central aspect of Riley's work is the extension of the concept of lawful lens to arbitrary lawful optics [34, §3].This extension works exactly the same for the optics we define here, so we do not address it explicitly in this paper.A first reasonable notion of lawfulness for the case of mixed optics for two actions ( Clarke, Elkins, Gibbons, Loregian, Milewski, Pillmore, Román Profunctor Optics: a Categorical Update

Further work
In terms of functional programming, optics of different kinds compose using polymorphic function composition.A categorical account of how optics of different kinds compose into optics is left for further work.Specifically, it should be able to explain the "lattice of optics" described in [3,31].Some preliminary results have been discussed by [36], but the proposal to model the lattice is still too ad-hoc to be satisfactory.The topic of lawfulness [34, §3] and how it relates to composition and mixed optics is also left for further work.
The relation between power series functors and traversables is implicit across the literature on polynomial functors and containers.It can be shown that traversable structures over an endofunctor T correspond to certain parameterised coalgebras using the free applicative construction [17].We believe that it is possible to refine this result to make our derivation for traversals more practical for functional programming.
It can be noted that lenses are the optic for products, functors that distribute over strong functors.Traversals are the optic for traversables, functors that distribute over applicative functors.Both have a van Laarhoven representation in terms of strong and applicative functors respectively.A generalization of this phenomenon needs a certain Kan extension to be given a coalgebra structure [36,Lemma 4.1.3],but it does not necessarily work for any optic.
Optics have numerous applications in the literature, including game theory [13], machine learning [9] and model-driven development [39].Beyond functional programming, enriched optics open new paths for explorating applications of optics.Both mixed optics and enriched optics allow us to more precisely adjust the existing definitions to match the desired applications.

Appendix: Haskell implementation
Let V be a cartesian closed category whose objects model the types of our programming language and whose points 1 → X represent programs of type X.The following is an informal translation of the concepts of enriched category theory to a Haskell implementation where a single abstract definition of optic is used for a range of different examples.The code for this text can be compiled under GHC 8.6, using the libraries split and delay.It includes an implementation of optics and all the examples we have discussed (Figures 1, 7, 8 and 9).
The complete code can be found at https://github.com/mroman42/vitreaIn Haskell, we define a class of higher-order type constructors that represent a category.Here, the objects for our category are selected from Haskell types by the constraint objc.Hom-objects are selected by the two-argument type constructor c.We then ask that they have a identity, unit, and a composition, comp.We define the monoidal category relative to a bifunctor representing the tensor and an object representing the unit.We ask for all the coherence maps, i.e. alpha for the associator.= > c ( f p ( f q x ) ) ( f ( p 'o ' q ) x ) multiplicatorinv :: ( objc x , objm p , objm q ) = > c ( f ( p 'o ' q ) x ) ( f p ( f q x ) )

Concepts of enriched category theory
Monoidal actions are bifunctors with extra maps representing the coherence conditions, e.g.unitor for the oplaxator.The isomorphism between existential and profunctor optics can be explicitly constructed from Lemma 4.12.dimap @objc @c @objd @d l r .tambara @objc @c @objd @d @objm @m @o @i ( unitorinv @objm @m @o @i @objc @c @f ) ( unitor @objm @m @o @i @objd @d @g ) ) We used the TypeApplications language extension to explicitly pass type parameters to polymorphic functions.

Combinators
After constructing optics, an implementation should provide ways of using them.Many optics libraries, such as Kmett's lens [20], provide a vast range of combinators.Each of these combinators works on some group of optics that share a common feature.For instance, we could consider all the optics that implement a view function, and create a single combinator that lets us view the focus inside a family of optics.This may seem, at first glance, difficult to model.We do not know, a priori, which of our optics will admit a given combinator.However, the fact that Tambara modules are copresheaves over optics suggests that we can use them to model ways of accessing optics; and in fact, we have found them to be very satisfactory to describe combinators in their full generality.Remark 6.6.As an example, for any fixed A and B, consider the profunctor P A,B (S, T ) := (S → A).It can be seen as modelling the view combinator that some optics provide.
newtype Viewing a b s t = Viewing { getView :: s -> a } instance Profunctor Any ( ->) Any ( ->) ( Viewing a b ) where dimap l _ ( Viewing f ) = Viewing ( f .l ) If we want to apply this combinator to a particular optic, we need it to be a Tambara module for the actions describing the optic.For instance, we can show that it is a Tambara module for the cartesian product, taking C = D = M; this means it can be used with lenses in the cartesian case.
In other words, lenses can be used to view the focus.

Table of combinators
The names of our combinators try to match, where possible, the names used by Kmett's lens library [20].Replaces the target, producing a monadic effect.

Table of optics
We can consider all of these optics in the case where some cartesian closed W is both the enriching category and the base for the optic.This case is of particular interest in functional programming.

Figure 4 :
Figure4: A type-variant lens that targets the contents of a value paired with creation and modification timestamps.The lens is constructed from two functions viewContents and updateContents.

Figure 5 :
Figure5: The common structure of an optic.We could provide semantics for diagram of this kind in terms of profunctors, see[37].
categories C and D by means of strong monoidal V-functors ( L ) : M → [C, C] and ( R ) : M → [D, D]; and let us write

Figure 6 :
Figure 6: Tableofoptics, together with their explicit description and their generating monoidal actions.The bullet represents some monoidal action; the brackets represent some monoidal action from the opposite category.

Definition 3 . 3 .Proposition 3 . 4 .
A monoidal lens [38, §2.2] in a symmetric monoidal category C is a view and update pair where the view is a commutative comonoid homomorphism, MonLens ⊗ ((A, B), (S, T )) := CCom(S, A) × C(US ⊗ B, T ).Here U represents the forgetful functor U : CCom → C. Monoidal lenses in a symmetric monoidal category are a particular case of Definition 3.1.

Figure 7 :
Figure 7: A polymorphic family of type-variant monadic lenses for the IO monad is used to track how a data holder (Timestamped) is accessed 2.5 seconds after creation.

Figure 8 :
Figure 8: Fisher's iris dataset [8], samplying lengths and widths of sepals and petals of three species of iris.A classifying lens (measure) is used both for accessing the measurements of a point in the iris dataset and to classify new measurements (not already in the dataset) into a species (Versicolor).

Figure 9 :
Figure 9: The composition of a traversal (each) with a prism (asAddress) and a lens (street) is used to parse a collection of strings and modify one of the resulting subfields.

Remark 3 .
23.The V-functor Pw : [N, C] → [C, C] is actually a monoidal action thanks to the fact that two power series functors compose into a power series functor.

∼
= {Product distributes over colimits} m n1,...,nm •) : [N, C] ⊗ [N, C] → [N, C] of C n and D n can be written as follows; and the relevant copowers exist because of C having an initial object.m n1,...,nm

Figure 10 :
Figure 10: Following the previous Example 8, a kaleidoscope (representative) is composed with an algebraic lens to create a new point in the dataset by aggregating measurements with some function (mean, maximum) and then classifying it.

Definition 3 . 33 .
Let C be an arbitrary V-category.Getters (morphisms C(S, A)) are degenerate optics for the trivial action on the covariant side.Reviews (morphisms C(B, T )) are degenerate optics for the trivial action on the contravariant side.In other words, we can obtain plain morphisms as a particular case of optic when M = 1 and D = 1 or C = 1, respectively.

Definition 4 . 1 .
Let (M, ⊗, I) be a monoidal V-category with two monoidal actions ( L ) : M ⊗ C → C and ( R ) : M ⊗ D → D. A generalized Tambara module consists of a V-profunctor P : C op ⊗ D → V endowed with a family of morphisms α M,A,B : P (A, B) → P (M L A, M R B) V-natural in A ∈ C and B ∈ D and V-dinatural in M ∈ M, which additionally satisfies the two equations

Remark 4 . 3 .
Before the definition, let us recall the axioms for a monoidal V-action ⊘ :M ⊗ C → C of a monoidal V-category (M, ⊗, I) with coherence isomorphisms (a, λ, ρ) to an arbitrary category C. Let ϕ A : A ∼ = I ⊘ A, ϕ M,N,A : M ⊘ (N ⊘ A) ∼ = (M ⊗ N ) ⊘ A,be the structure V-natural isomorphisms of the monoidal action.Note that the following are precisely the axioms for a strong monoidal functor M → [C, C] written as M ⊗ C → C; they are simplified by the fact that [C, C] is strict.

N,K ⊘A Definition 4 . 4 .
We start by constructing the underlying V-functor of the comonad Θ : Prof (C, D) → Prof (C, D).Consider first the V-functor
The unit and multiplication of the promonad are then obtained by whiskering the unit and multiplication of the monad with the Yoneda embedding; that is, (η•y) : y → T •y and (µ•y) : T •T •y → T • y.The diagrams for associativity and unitality for the promonad are the whiskering by the Yoneda embedding of the same diagrams for the monad.In fact, the same reasoning yields that, for any P : D op → [A, V], Ť ⋄ P ∼ = (T • y) ⋄ P ∼ = Lan y (T • y) • P ∼ = T • P.

Remark 4 . 13 .
As a very simple special case of the Double Yoneda construction, the Haskell typeforall f .Functor f = > f a -> f bis isomorphic to the simple function type a -> b[25].It is straightforward for a functional programmer to construct the two witnesses to the isomorphism: the functorial action in one direction, and instantiation to the identity functor in the other.

class
Profunctor p = > Cartesian p where first ' :: p a b -> p (a , c ) (b , c ) second ' :: p a b -> p (c , a ) (c , b ) L ) : M ⊗ C → C and ( R ) : N ⊗ D → D is to use a cospan C → E ← D of actions to push the two parts of the optic into the same category and then consider lawfulness in E.

Definition 6 . 1 (
[18,  §1.2], see also[43]).A V-category C consists of a set Obj(C) of objects, a hom-object C(A, B) ∈ V for each pair of objects A, B ∈ Obj(C), a composition law C(A, B) × C(B, C) → C(A, C) for each triple of objects, and an identity element 1 → C(A, A) for each object; subject to the usual associativity and unit axioms.class Category objc c where unit :: ( objc x ) = > c x x comp :: ( objc x ) = > c y z -> c x y -> c x z

Definition 6 . 5 .
Definition 2.1 has now a direct interpretation in more generality.Note how the coend is modeled as an existential type in x using a GADT.data Optic objc c objd d objm m o i f g a b s t where Optic :: ( MonoidalAction objm m o i objc c f , MonoidalAction objm m o i objd d g , objc a , objc s , objd b , objd t , objm x ) = > c s ( f x a ) -> d ( g x b ) t -> Optic objc c objd d objm m o i f g a b s t 6.2 Mixed profunctor optics We can implement Tambara modules (Definition 4.1) and profunctor optics using the profunctor representation theorem (Theorem 4.14).class ( MonoidalAction objm m o i objc c f , MonoidalAction objm m o i objd d g , Profunctor objc c objd d p ) = > Tambara objc c objd d objm m o i f g p where tambara :: ( objc x , objd y , objm w ) = > p x y -> p ( f w x ) ( g w y ) type ProfOptic objc c objd d objm m o i f g a b s t = forall p .( Tambara objc c objd d objm m o i f g p , MonoidalAction objm m o i objc c f , MonoidalAction objm m o i objd d g , objc a , objd b , objc s , objd t ) = > p a b -> p s t ex2prof :: forall objc c objd d objm m o i f g a b s t .Optic objc c objd d objm m o i f g a b s t -> ProfOptic objc c objd d objm m o i f g a b s t ex2prof ( Optic l r ) = prof2ex :: forall objc c objd d objm m o i f g a b s t .( MonoidalAction objm m o i objc c f , MonoidalAction objm m o i objd d g , objc a , objc s , objd b , objd t ) = > ProfOptic objc c objd d objm m o i f g a b s t -> Optic objc c objd d objm m o i f g a b s t prof2ex p = p ( Optic ) :: s -> ( Viewing a b a b -> Viewing a b s t ) -> a (^.) s l = getView ( l ( Viewing id ) ) s ) :: s -> (Viewing a b a b -> Viewing a b s t) -> a View a single target.(?.) :: s -> (Previewing a b a b -> Previewing a b s t) -> Maybe a Try to view a single target; this can possibly result in failure.(.~) :: (Setting a b a b -> Setting a b s t) -> b -> s -> t Replace a target with a given value.(%~) :: (Replacing a b a b -> Replacing a b s t) -> (a -> b) -> (s -> t) Replace a target by applying a function.(.?) :: (Monad m) => (Classifying m a b a b -> Classifying m a b s t") -> b -> m s -> t Classifies the target into a complete instance.(>-) :: (Aggregating a b a b -> Aggregating a b s t) -> ([a] -> b) -> [s] -> t Aggregates the whole structure by aggregating the targets.(.!) :: (Monad m)=> (Updating m a b a b -> Updating m a b s t)-> b -> s -> m t > Either a t) , (b -> t) 3.16 Coalgebraic prism (s -> Either a (c t)) , (b -> t) 3.8 Grate ((s -> a) -> b) -> t 3.29 Glass ((s -> a) -> b) -> s -> t 3.31 Affine Traversal s -> Either t (a , b -> t) 3.24 Traversal s -> (Vec n a, Vec n b -> t) 3.20 Kaleidoscope (Vec n a -> b) -> (Vec n s -> t) 3.26 Setter (a -> b) , (s -> t)