The more legs the merrier: A new composition for symmetric (multi-)lenses
DDavid I. Spivak and Jamie Vicary (Eds.):Applied Category Theory 2020 (ACT2020)EPTCS 333, 2021, pp. 92–107, doi:10.4204/EPTCS.333.7 © Michael Johnson & Robert RosebrughThis work is licensed under theCreative Commons Attribution License.
The more legs the merrier:A new composition for symmetric (multi-)lenses
Michael Johnson
CoACT, Departments ofMathematics and ComputingMacquarie University [email protected]
Robert Rosebrugh
Department of Mathematicsand Computer ScienceMount Allison University [email protected]
This paper develops a new composition of symmetric lenses that preserves information which isimportant for implementing system interoperation. It includes a cut-down but realistic example ofa multi-system business supply chain and illustrates the new mathematical content with analysis ofthe systems, showing how the new composition facilitates the engineering required to implement theinteroperations. All of the concepts presented here are based on either pure category theory or onexperience in solving business problems using applied category theory.
Lenses are a category theoretic construct and are used in a very wide variety of applications. Lenses comein a wide range of forms, but each kind of lens has a composition (associative, and with identities), andso the various lenses form the morphisms of categories, most often with objects which are themselvescategories, usually representing states and transitions of some systems. Among the kinds of lenses wewill use here are asymmetric, symmetric, and multiary lenses.Symmetric lenses compose to, unsurprisingly, form new symmetric lenses. Symmetric lenses areusually represented as spans of asymmetric lenses. Indeed, from the very beginning, symmetric lenseshave had various ad-hoc definitions, but in all cases the authors noted that an alternative approach wouldbe to define them as equivalence classes of spans of asymmetric lenses.In many applications, the fact that a symmetric lens might also be represented as a co span of asym-metric lenses is important, especially for implementation purposes. However, the composition of sym-metric lenses does not preserve the property that the lenses can be represented by cospans — two suchsymmetric lenses may (and frequently do) compose to form a symmetric lens which cannot be repre-sented as a cospan of asymmetric lenses. Thus preserving the factorisation to show how cospans ofasymmetric lenses might be used in implementations becomes important.In 2018, the first work on multilenses was begun. Multilenses can be represented as multi-spans ofasymmetric lenses (often called wide spans, these multi-spans are spans with an arbitrary finite numberof legs). In this paper we analyse a small but realistic example of a supply chain in which the cospanrepresentations would be ‘composed away’ by ordinary symmetric lens composition, and introduce a newkind of composition which we call fusion in which two ordinary symmetric lenses (spans with two legs)fuse to form a multilens with three legs preserving the cospan representations, and more generally, twomultilenses, spans with say m and n legs, fuse to form a multilens with m + n − fusion , of multilenses, which in particulargives a new composition for symmetric lenses. We still refer to it as a kind of composition because itcontains all the information of the composite, but it has more, preserving, unlike normal compositions,some important information about the makeup of the individual lenses that were composed. This extrainformation is shown in Section 8 to be just what is needed to preserve cospan representations when theyexist, and so to facilitate engineering practice.After a brief interlude in Section 9 to review some other examples of fusion-like compositions, weconclude and outline some future work in Section 10, briefly describing how cospans among the feet ofa multispan can be recovered unambiguously from the appropriately fused multispan. This emphasisesthe engineering importance of using fusion rather than composition.The paper requires only modest category theoretic background for which we refer readers to anystandard text. One particular category theoretic notion we use repeatedly, above and below, is span . A span in a category is just a pair of arrows with common domain. A cospan is, of course, a pair of arrowswith common codomain. A wide span is a collection of a finite number of arrows with common domain,and similarly a wide cospan is a collection of a finite number of arrows with common codomain. We willfrequently talk about spans or cospans of asymmetric lenses. Asymmetric lenses are defined in Section3, but for now note that an asymmetric lens is a functor, normally called the Get of the lens, and somefurther structure. In our categories of lenses the arrows are lenses, and they are oriented in the directionof the lenses’ Gets. Thus a span of asymmetric lenses has, inter alia, two Gets (one for each lens) with acommon domain. We begin with an example which we will use to illustrate the concepts presented in this paper. Theexample is based on real systems, but they have been cut down to the essential details required to capturethe ideas presented here.Supply chains, especially global supply chains, are very much in the economic news at presentbecause of the disruptions to production and distribution caused by the corona virus crisis. In manycases modern supply chains are managed through system interoperations, with individual organisationsowning and operating their own information systems, but sharing enough information for those systemsto interoperate automatically. For example, two businesses, a supplier and a customer, might both keeptrack of the amount of stock available on a customer’s premises so that further stock can be supplied in ajust in time (JIT) manner. To maintain the consistency of the two representations of the customer’s stocklevels, information is exchanged between the two systems. This is system interoperation in action, and, aswe will see later, it is mathematically captured by lenses — certain kinds of bidirectional transformations.For our massively simplified businesses, imagine a supplier called ABC Frames. It provides the basicstructure, the chassis if you will, for a variety of products that are manufactured by other businesses whichmake up ABC Frames’ customers. One of those customers is XYZ Manufacturing, which is operatedas several distinct business entities, XYZ Warehouse, XYZ Logistics and XYZ Production being the4 Themore legsthe merrier
ABC Frames XYZ Warehouse XYZ Logistics Location / / / / X (cid:15) (cid:15) X Frame / / / / FrameLocation (cid:15) (cid:15)
X ZOrdersX (cid:2) (cid:2) (cid:2) (cid:2) ✆✆✆✆✆✆✆✆✆✆
Orders Z (cid:28) (cid:28) (cid:28) (cid:28) ✾✾✾✾✾✾✾✾✾✾
X ZXYZX y y sssssss XYZ Z % % ❑❑❑❑❑❑❑ XYZY (cid:15) (cid:15)
OrdersXYZ (cid:15) (cid:15) (cid:15) (cid:15)
OrdersY (cid:30) (cid:30) (cid:0) (cid:0)
AssemblyXYZ (cid:15) (cid:15) (cid:15) (cid:15) ✤✤ X $ $ ■■■■■■■■■■■ X z z ✉✉✉✉✉✉✉✉✉✉✉ XYZ $ $ ■■■■■■■■■■ XYZ z z ✉✉✉✉✉✉✉✉✉✉ Figure 1: Three (simplified) business entities interoperating via two cospans of lensesbusinesses we will consider here.A true representation of ABC Frames will, like most businesses, involve systems which track hun-dreds, and often many thousands of different types of entities, along in each case with their many at-tributes (for example, colour, dimensions, location, serial number, base price, etc). For our purposes wefocus on a single type of frame, called here just
Frame s. These frames almost certainly have many at-tributes including those above, but for now we will just consider location. (Other attributes can be easilymanaged too, but will just clog up our pictures if we depict them.) So, for our purposes we might thinkof ABC Frames as having at any instant a set of frames, with each frame having a specified location. Forour purposes ABC Frames’ information system stores two sets and a function between them
Frame −→ Location . XYZ Manufacturing, in its simplified form, takes frames which they call X , and assembles them withother products called simply Y and Z to produce a consumer product known as XYZ. In particular, XYZWarehouse keeps stocks of X , Y and Z , along with various attributes of each instance of those stocks (theirserial numbers, colours, and so on) which we will not record here. The warehouse information systemalso calculates from its known stocks the product X × Y × Z which is useful for XYZ’s consumer facingoperations because it shows all of the possible available combinations of X , Y and Z items that mightbe assembled and provided to a potential customer. XYZ Warehouse’s information system also storesbriefly some information about orders, but we will return and fill that in later. So, for now, mathematicallyspeaking, XYZ Warehouse’s information systems stores three sets, along with their product and theproduct projections (all of which can be calculated as required from the three sets).XYZ Logistics, also known as XYZ Sales because it is the principal interface with XYZ’s customers,assembles orders placed by customers after, of course, detailed discussions with those customers aboutcustomers’ needs and desires, frequently consulting XYZ’s current catalogue, which is really just a copycalled XYZ of the product X × Y × Z calculated by XYZ Warehouse. So XYZ Logistics’ informationsystem stores a set whose value is kept consistent with XYZ Warehouse’s calculated product by systeminteroperations (a lens in fact). In addition, XYZ Logistics keeps track of customer orders, so it maintainsa set usually called Assembly Order (or just
Assembly for short) whose elements are casually calledorder-lines or order items, which should be a subset of
XYZ (a subset because, of course, we don’t wanttwo orders for the same assembled product — each assembly is unique and can only be sold once). Asichael Johnson &Robert Rosebrugh 95you can imagine, XYZ Logistics does much more, and has its “Logistics” name, and uses terms like
Assembly for orders, because it looks after many logistical issues including the transfer of products fromthe warehouse to XYZ Production, but we don’t need to discuss these things here and they have beenelided. Mathematically, the much simplified information system for XYZ Logistics contains a set
XYZ and a subset of that set representing the current order items:
Assembly / / / / XYZ . The eagle-eyed among readers will have spotted another concern. Since the catalogue,
XYZ con-tains all possible assemblies from products contained in the warehouse, customers might order distinctassemblies which nevertheless contain the same instance of a particular product. For example, two dif-ferent customers might order two different assemblies both of which are built on the frame with serialnumber 4097. We need to guard against this as both orders can’t be satisfied — there is only one frame4097. This is where the “extra information” mentioned above in discussing XYZ Warehouse’s informa-tion system comes into play. XYZ Warehouse also keeps a local copy called
Orders of XYZ Logistics’
Assembly , maintained again by system interoperations, along with the corresponding subset inclusion of
Orders into X × Y × Z . Since that product comes with its product projections in XYZ Warehouse, the in-formation system there can see the composite of the inclusion with each of the product projections, and,as part of its inbuilt constraints, it requires that those compositions are monic (injections). Any attemptto enter an order item that violates that constraint will be rejected, and via the systems interoperations,a customer will be unable to order an assembly containing, for example, frame 4097 if there is alreadyanother extant order for an assembly using that frame. Mathematically the full version of the fragment ofXYZ Warehouse’s information system that we will be considering is summarised in the diagram below. X ZOrdersX (cid:127) (cid:127) (cid:127) (cid:127) ⑧⑧⑧⑧⑧⑧⑧⑧⑧⑧⑧
Orders Z (cid:31) (cid:31) (cid:31) (cid:31) ❄❄❄❄❄❄❄❄❄❄❄❄
X ZXYZX w w ♦♦♦♦♦♦♦♦♦ XYZ Z ' ' ❖❖❖❖❖❖❖❖❖ XYZY (cid:15) (cid:15)
OrdersXYZ (cid:15) (cid:15) (cid:15) (cid:15)
OrdersY ~ ~ That completes our summary of XYZ Manufacturing’s information systems, and we have seen thevery simple information systems maintained by ABC Frames, but to complete our automated supplychain we need to see how the two companies’ systems interact, and it is very simple. Among the locationswhere ABC Frames might keep track of frames is XYZ Warehouse. So in ABC Frames there is anelement 1 −→ Location which picks out XYZ’s warehouse, and the pullback1
Location / / / / X (cid:15) (cid:15) X Frame / / / / FrameLocation (cid:15) (cid:15) calculates the subset of
Frame s which are the frames located at XYZ Warehouse. That should of coursecorrespond to X in XYZ’s own systems and system interoperations are used to keep those two setsconsistent. This supports for these two companies their version of the JIT supply system described at thebeginning of this section.Although this example is vastly simplified, it does model many interesting aspects of category theo-retic information systems interoperation, including, as we will see below, symmetric lenses, multilenses,cospan implementations of interoperations, amendment lenses, and so on. A summary of the three sim-plified business entities alonng with rough indications of the lenses between them used for maintaining6 Themore legsthe merrierinteroperations (excluding part of the amendment lens synchronising Asssembly and
Orders ) is shown inFigure 1.Before saying more about all this we review the relevant concepts from earlier work, and develop thenew theory required for this paper.
Lenses are used to maintain synchronisation between (or in the case multilenses, among) different sys-tems. In asymmetric lenses, one of the systems (the one with state space S below) has all the informationrequired to reconstruct the other (the one with state space V below). An operation, usually called “Get”and frequently denoted G , gives for any state of the system S , the corresponding state of the system V . Inthe reverse direction, we would not expect a V state to contain enough information to recreate an entire S state. Instead, the operation usually called “Put” provides a new state s ′ of S given an old state s of S and a change of state in V from Gs to some new state v ′ , such that the new states of S and V , s ′ and v ′ ,are again synchronised.Naturally, state spaces will be represented here as categories — a state of a system is an object ofthe state space, and arrows of the state space are state transitions (and state transitions can be composedassociatively, and there are identity transitions corresponding to no-change). Thus the state transition in V just mentioned is an arrow Gs / / v ′ in V .Database view updating [2] provides a typical (and longstanding) example: Suppose that S is thestate space of the information system of ABC Frames, one of the organisations discussed in the previoussection. The object X of the previous section is the state space of a view of S . A state of X is just a set,the current set of frames located at the XYZ Warehouse according to the current state of the informationsystem S . And the pullback above shows how to calculate X from a current state of ABC Frame’sinformation system (as discussed in Section 2, a state of ABC Frame’s information system is just afunction Frame −→ Location ). The Get of this view is calculated by the pullback, which in databaseterms is simply the query “ select Frame where Location equals XYZ Warehouse ”.If the view X is changed, then the Put needs to construct sets Frame and
Location and a function
Frame −→ Location . The most natural choice of Put in this case starts from the old function
Frame −→ Location , leaves
Location unchanged, changes
Frame to correspond to the new X by adding or deletingelements as required, retains the values of the function for all those elements of Frame that remain inthe new X , and assigns any extra elements of X to have location XYZ Warehouse (since if the set X isintended to be the result of the above query, any extra (new) elements in X can be assumed to located atXYZ Warehouse).All of this can be formalised easily using the theory of database modelling via EA-sketches [12]in which diagrams like those from the previous section are the base graphs of sketches, limits are usedto ensure that things like products and monics are appropriately realised, colimits are used to defineattributes, and the state spaces just described are models of the sketches, that is, full subcategories offinite set-valued functor categories for which the functors preserve finite limits and finite coproducts.We turn now to the formal definition of asymmetric lenses. For readers who are most familiar withearly work on lenses [21, 20] or with lenses as implemented in Haskell, this definition might come as asurprise, but it elegantly captures the generality required in clear category theoretic terms. Asymmetriclenses, as defined here, are sometimes called d-lenses or delta lenses [7], and unify a wide range ofdifferent types of lenses [13]. Definition 1 (Clarke [3]): An asymmetric lens is a commutative triangle of functors, as depicted below ichael Johnson &Robert Rosebrugh 97 left, in which F is a discrete opfibration, P is bijective on objects, and G and P are called the Get andthe Put respectively. SV G t t ✐✐✐✐✐✐✐✐✐ Λ S P * * ❯❯❯❯❯❯❯❯❯ Λ V F (cid:15) (cid:15) V V G t t ✐✐✐✐✐✐✐✐ Λ V P * * ❯❯❯❯❯❯❯❯ Λ V F (cid:15) (cid:15) SV G t t ✐✐✐✐✐✐✐✐✐ Λ S P * * ❯❯❯❯❯❯❯❯❯ Λ V F (cid:15) (cid:15) The category Λ is, up to equivalence, a category with the same objects as S and with an arrow α from s to s ′ if and only if α : Gs / / Gs ′ in V (using the notation s ′ from the beginning of this section). Thespan ( Λ , F , P ) is a co-functor [1] from V to S . For further motivation and details we refer the reader to [3].As noted there, composition of asymmetric lenses is defined by simply composing the Gets and pullingback the second Put, P , along the first lens’s discrete opfibration, F (see the above right diagram). Thus,there is a category ALens whose objects are categories and whose arrows are asymmetric lenses, orientedin the direction of the Get (so the above left triangle is an arrow of
ALens from S to V ). Lenses, as just defined, are examples of bidirectional transformations [10]. To reiterate, a bidirectionaltransformation maintains consistency between two systems as one or the other changes, and the functorpart and the cofunctor part of an asymmetric lens embody the two updates required, one in each direction,to restore consistency after a change of state of one system or the other. As we’ve noted, such lenses areoften called asymmetric lenses to emphasise the asymmetry noted at the beginning of Section 3: A stateof one system, S , has all the information required to construct a state of the other system, V , and this isreflected in the fact that one of the updates, G , is simply a functor.While asymmetric lenses do arise in real world applications of bidirectional transformations, thereare many important cases where neither system has the information to reconstruct the other completely.Instead, each system “knows” things that the other system does not. What’s required is a symmetric lens[11, 8]. As was conjectured in both the papers just cited, and in [9], a symmetric lens can be definedas an equivalence class of spans of asymmetric lenses [14]. In this paper we will elide the details aboutthe equivalence (full details are available in [14]) and work with representatives of equivalence classes.Again, the best available modern treatment is due to Bryce Clarke. Definition 2
This formulation is due to Clarke [4]:
A (representative for a) symmetric lens is a span ofasymmetric lenses as shown, SV G t t ✐✐✐✐✐✐✐✐✐ Λ S P * * ❯❯❯❯❯❯❯❯❯ Λ V F (cid:15) (cid:15) S V G * * ❯❯❯❯❯❯❯❯❯ Λ S P t t ✐✐✐✐✐✐✐✐✐ Λ V F (cid:15) (cid:15) in which the objects are categories, the arrows are functors, the vertical arrows F and F are discreteopfibrations, and the functors P and P are bijective on objects. This “bowtie” representation of symmetric lenses turns out to be particularly convenient. For ex-ample, as a bidirectional transformation, a symmetric lens should show how to restore consistency if astate of either V or V is changed. These two operations have variously been called the Rightward andLeftwards [11] and Forwards and Backwards [8] propagations. Each propagation is easily visible in the8 Themore legsthe merrierbowtie, with, for example, the Forwards propagation given by the span ( Λ , F , G P ) , or in short, theSouth-East diagonal G P . In more detail: The systems with state spaces V and V are synchronisedwhen there is an s in S with the current states of V and V equal to G s and G s respectively. If V thenchanges state via say an α : G s / / v ′ , then that determines a unique arrow of Λ , ˆ α : s / / s ′ and G P ˆ α is an arrow of V , of the form G s / / v ′ . Furthermore, the new states v ′ and v ′ are synchronised by s ′ .Synchronisation has been restored by the Forward propagation G P .This might be a convenient moment to say a few more words about the equivalence relation thatwe are mostly suppressing in this short version to ease the reader’s burden. A symmetric lens is a bidi-rectional transformation between V and V , while S is generally considered to be hidden coordinationinformation. If two bowtie representations between V and V have the same Forwards and Backwardspropagations then they should be considered to be representatives of the same abstract symmetric lenseven if they happen to manage their coordination via different categories S and S . Again, we referreaders interested in full details about the required equivalence relation to [14].Another convenience of the bowtie representation is that it shows immediately how symmetric lensescompose. In fact, it shows that in two distinct, but equivalent ways. First, operationally, the Forwardpropagation described two paragraphs ago results in an arrow of V , which can be in exactly the samemanner Forward propagated along a symmetric lens from V to V defining a composite Forward prop-agation. Similarly, Backward propagations can be iterated thus determining, operationally, a compositesymmetric lens from V to V . This can be shown to be equivalent to the composite span of asymmetriclenses described in Remark 4 below using lens structures on the pullback in cat . First we describe these“pulled back” lenses and their basic properties. Proposition 3
Given a cospan of asymmetric lenses as shown S ′ V ′ G ′ t t ✐✐✐✐✐✐✐✐ Λ ′ S ′ P ′ * * ❯❯❯❯❯❯❯❯❯ Λ ′ V ′ F ′ (cid:15) (cid:15) = S V G * * ❯❯❯❯❯❯❯❯❯ Λ S P t t ✐✐✐✐✐✐✐✐✐ Λ V F (cid:15) (cid:15)
1. Each lens pulls back along the other lens’s Get to give a lens2. The resulting square of asymmetric lenses commutes in
ALens , and will be referred to as the“pullback” of the cospan3. The cospan itself determines operationally Forwards and Backwards propagations4. And the propagations determined by the cospan and by its “pulled back” span coincide.
Proof.
We give brief proof outlines:1. This is proved by explicitly constructing the Puts in [14], but here we just outline the simple proofdue to Clarke [3]: Part 1 follows immediately from the pullback pasting lemma and the facts thatdiscrete opfibrations pull back along functors to give discrete opfibrations and bijective on objectsfunctors pullback along functors to give bijective on object functors.2. The Gets of the two sides of the square commute by construction (the Gets form a pullback squarein cat ) and it’s easy to see from the explicit construction of the Puts along the two sides of thesquare that the compositions of the cofunctors coincide too.ichael Johnson &Robert Rosebrugh 993. For a cospan labelled as above, we call objects s of S and s ′ of S ′ synchronised when G s = G ′ s ′ .If s and s ′ are synchronised, and α : s / / r is a change of state of the system with state space S ,then the Forward propagation of α is the Put, P ′ , of G α : G ′ s ′ / / G r , which will be an arrow of S ′ with domain s ′ and whose codomain is then synchronised with r . The Backward propagation isdefined similarly.4. Finally, by the constructions of pullbacks in cat , s and s ′ are synchronised by the pulled backspan if and only if they are synchronised by the given cospan. Furthermore, by inspection, thetwo Forward propagations coincide, and by symmetry the same inspections shows that the twoBackward propagations coincide.The inverted commas around “pullback” are to remind us that while the pullback in cat , along withthe lenses constructed on its pullback projections, might look like a pullback diagram in ALens , it is notnecessarily a pullback in that category (the universally determined mediating functors do not in generalhave canonical lens structures on them).
Remark 4
Given composable representatives of symmetric lenses, that is, spans in
ALens which agreeon one of their feet (as in V = V ′ in the proposition), they can be composed using the “pullback” of thecospan exactly as one does for span composition in cat . In more detail: Imagine that the two trianglesin the proposition are the right side of the bow-tie displayed in Definition 2, and the left side of a similarbowtie in which all the labels have added primes, then the pullback of the proposition gives a new span ofasymmetric lenses with peak T say, between S and S ′ . As in ordinary span composition these asymmetriclenses can be composed with the asymmetric lenses S / / V and S ′ / / V ′ to yield the composite spanof asymmetric lenses with peak T and feet V and V ′ . Here is the picture, labelling the various lenseswith their Gets, and in which H and H ′ are the pullback projections in cat . S S ′ TS H y y ssssssss T S ′ H ′ % % ❑❑❑❑❑❑❑❑ S V = V ′ G % % ❑❑❑❑❑❑ S S ′ S ′ V = V ′ G ′ y y ssssss SV G y y sssssss S ′ V ′ G ′ % % ❑❑❑❑❑❑❑ Furthermore, using (4) from the proposition, the operational propagations of the composite span agreewith the composite of the operational propagations as described just before the proposition.
In the previous section we saw that every cospan of asymmetric lenses yields, by pullback, a span ofasymmetric lenses, that is, a representative for a symmetric lens. In fact, the cospan presentation of anasymmetric lens is especially valuable and is the main way system interoperations are actually built.To revisit our example from Section 2, we have already seen that there is an asymmetric lens betweenABC Frames and the (possibly imaginary, but frequently built) system X . Furthermore, there is anasymmetric lens from XYZ Warehouse to X . The Get of that lens is just a projection from among allthe data stored at XYZ Warehouse, and returns simply the current state of the set X in XYZ Warehouse.The Put starts from a known state of XYZ Warehouse and a new state of X , and constructs a new stateof XYZ Warehouse by changing its set X to match, leaving the sets Y and Z unchanged, recalculatingthe product X × Y × Z , and usually leaving the set of Orders unchanged, but if some elements of X have00 Themore legsthe merrierbeen deleted, and if there are orders depending on those elements of X , then those orders are also deleted(called by database people a “cascading delete”). Notice that if instead new elements of X had beeninserted, then Orders would not change, but the injection into X × Y × Z would be adjusted to accountfor its new larger codomain.Thus we have a cospan of asymmetric lenses between ABC Frames and XYZ Warehouse. We couldsay now, following the previous section, that we “pullback” the span to obtain a representative for asymmetric lens, thus providing interoperations between ABC Frames’ and XYZ Warehouse’s systems.That is indeed theoretically true. The resulting system at the peak of the span T is sometimes calledthe federated information system because it is the state space for the system that combines all of theinformation held at ABC Frames with all of the information held at XYZ Warehouse, subject only toensuring that those two subsystems remain consistent via the same X state. Such symmetric lenses aretheoretically important because we can reason with them and prove properties of the combined system(for example, that certain things remain consistent or that certain operations avoid deadlock or . . . ). Butthese systems are hardly ever built. To begin with, ABC Frames and XYZ are separate companies, andare unlikely to want to, or indeed be able to, break commercial-in-confidence agreements and share alldata that they might hold. There are commercial, privacy, and cyber security [17], reasons, to name justa few, for not building the system T .Instead, the system X might be built, along with the two asymmetric lenses to it described above(one from ABC Frames and one from XYZ Warehouse). Or, alternatively, the Forward and Backwardpropagations from such a cospan can be implemented as message passing and through Applications Pro-grammer Interfaces (APIs) the messages can keep the two systems of the two companies synchronised.These options limit the exposure of each of the companies and their systems to the minimum required forthe system interoperations [17], and those system interoperations are in the interests of the efficienciesof both organisations (after all, we only build such systems if there is a commercial imperative).Of course, as noted in Proposition 3 part 4, the propagations determined by the cospan through X or by the span through the federated information system are the same. But the former is a minor pieceof engineering work, which can even be separated into three tasks: Implementing the small commonsystem X , and the two asymmetric lenses from ABC Frames to it (which can be done exclusively byABC Frames engineers) and from XYZ Warehouse to it (which can be done exclusively by XYZ Ware-house engineers). On the other hand, working with the federated system, either by constructing it or bysimulating propagations through it, is a major piece of work that is generally hard to partition into secureand independent tasks.The message of this section is that cospan representations of symmetric lenses are very much pre-ferred for engineering purposes.It is worth noting however, that not all symmetric lenses have cospan representations. The paper[15] establishes necessary and sufficient conditions for the existence of cospan representations. For now,suffice it to say, having a cospan representation is something that one wants to keep.And so there is another important point to note: The composition of symmetric lenses does notpreserve cospan representability. Two cospan representable symmetric lenses may compose to give asymmetric lens which is not in itself cospan representable.Again, the example from Section 2 provides an illustration.We will not work through the details here, but there is a cospan representation for the symmetric lensbetween XYZ Warehouse and XYZ Logistics. To make the example more realistic we have includedin this interoperation an example of half-duplex interoperation (see [5]). In short, XYZ Logistics is notpermitted to change the state of the catalogue XYZ — it is read-only. There is also an opportunity hereto introduce a non-trivial amendment lens (see [6]) between XYZ Warehouse and XYZ Logistics, butichael Johnson &Robert Rosebrugh 101to keep things simple let’s assume that the company XYZ enters, processes and fills single orders at atime (otherwise orders in XYZ Logistics might have to be reversed (amended) by XYZ Warehouse if themonic constraints in XYZ Warehouse were violated).The cospan of symmetric lenses between XYZ Warehouse and XYZ Logistics determines by “pull-back” a representative for a symmetric lens. The two symmetric lenses (between ABC Frames and XYZWarehouse, and between XYZ Warehouse and XYZ Logistics) can be composed, either by “pullingback” (creating an even larger federated system T ′′ ), or by composing the propagations, and it may bethat for whatever reason the composite symmetric lens is the subject of our interest. But note well: Thecomposite symmetric lens is not cospan representable. Presented merely with the composite symmetriclens (and so, no information about how XYZ Warehouse mediates the information between ABC Framesand XYZ Logistics) there is no simple shared data that the two organisations can synchronise upon. Thesuper federated system could be used in theory to build interoperations, but the information about theengineering appropriate cospans is gone.Perhaps it would be better if the example from Section 2 were treated as a multilens, since then allthree organisations, and their interactions, could be captured in a single mathematical entity. Definition 5
For n a positive integer, an n -lens consists of n asymmetric lenses f i with common domain S , such that f i : S / / A i . A 1-lens is an asymmetric lens f : S / / A . A 2-lens is a representative for a symmetric lens — aspan in ALens as in Definition 2.For an n -lens L = ( f i : S / / A i ) , since it is in general an n -wide span in ALens , we adopt, and adapt,the terminology usually used for parts of wide spans (including ordinary spans). Thus the f i are calledthe legs of L , and the A i are called the feet of L . The category S is called the peak of L . We call f the leftmost leg of L and f n the rightmost leg of L , and A the leftmost foot of L and A n the rightmost footof L . Of course, for n = L coincide, and are both f , and likewise A is both the leftmost and the rightmost foot of L . When n ≤
2, the “most” of leftmost or rightmost issuperfluous in normal usage, and it is common to say just “the left leg” or “the right foot” etc, and evenwhen n >
2, if there is little chance of confusion, we may still say “left” for “leftmost” and “right” for“rightmost”.For n > n -lens is a wide span in the category ALens . Relating this to previous work, an n -lens for n > n -lenses form the “special case” (wide spans of d-lenses) referred to in thefinal paragraph of [16]. Thus, for n > n -lenses are a specialisation of multiary lenses — the specialcase in which all amendments are trivial. It may be worth emphasising that this “special case” is whatthe authors see as the main case. There are occasionally circumstances in which non-trivial amendmentsare useful, and the paper [16] dealt with nontrivial amendments to have the broadest possible generalityand to link directly with the extant work of Diskin et al [6], but in this paper we restrict our attention tomultilenses: wide spans of asymmetric lenses without amendments. Definition 6 A multilens L is an n-lens for some (positive integer) n. If n > the multilens L is said tobe non-trivial .
02 Themore legsthe merrier
The multiary lenses of [16] compose, as shown there, with a multicategory [19] structure. In the termi-nology of this paper, using the composite defined in [16], an m -lens and an n -lens compose to give an ( m + n − ) -lens (think for example of “plugging” the left leg of one lens into the right leg of the otherwith those two legs “disappearing”). That composition is a generalisation of the usual composition ofsymmetric lenses, or indeed of spans or relations — a 2-lens composes with a 2-lens if the leftmost footof one equals the rightmost foot of the other, and the result is a ( + − ) -lens with peak a pullbackcalculated over the common foot (see Remark 4). Notice that in this familiar composition the commonfoot and the two legs to that foot all disappear (hence the subtraction of two in the count of legs).The simple, but important, change in this paper is the introduction of a new composition called fusionwhich retains the foot that has been composed over. Definition 7
Suppose L = ( f i : S / / A i ) is an m-lens and L ′ = ( f ′ i : S / / A ′ i ) is an n-lens with therightmost foot of L being equal to the leftmost foot of L ′ . Then the fusion of L and L ′ , denoted here simplyby the juxtaposition LL ′ , is the lens LL ′ = ( g i : S / / B i ) given as follows: LL ′ is an ( m + n − ) -lens withfeet B i = A i for i ≤ m, and B i = A ′ i − m + for i ≥ m. Let T be the pullback of f m along g with projectionsH and H ′ , then g i = f i H if i ≤ m, and g i = f ′ i − m + H ′ if i ≥ m. Remark 8
We record here a few basic results about the fusion operation.1. Well-definedness: The use of both i ≤ m and i ≥ m in the definition is deliberate, and is intendedto reinforce the sense of fusion. If i = m then B i = A i = A ′ i − m + by assumption, and g i = f i H = f ′ i − m + H ′ by Proposition 3 part 2, so the fusion is well-defined.2. Identities: Identity 1-lenses are, up to equivalence, left and right identities for fusion.3. Associativity: Up to span isomorphism in cat , the fusion operation is associative. The equivalencerelation presented in [14] (and mostly avoided here) is coarser than span isomorphism in cat ,and is a congruence for fusion (and for the composition of [16]), so fusion is also associative forequivalence classes of multilenses. (The calculations are tedious, but routine, and follow the pathtraced in [14], so they have been suppressed here.)We would like to emphasise that fusion is a minor change from multilens composition. Non-trivialmultilenses are fusable if and only if they are composable — fusion simply keeps the foot that onecomposes over along with the single (by Proposition 3 part 2) leg to that foot. It is still an operationwhich combines composable multilenses to get multilenses. But fusion often feels like a significantchange for people who are used to composing symmetric lenses because the fusion of two symmetriclenses is not a symmetric lens but rather a 3-multilens. This difference is exactly what we need forour applications. We will return to this in Section 9 where we illustrate a few other well-known fusionoperators for comparison purposes and to set readers’ minds at ease. We turn now to some basic examples of fusion, and then revisit the example of Section 2.What happens when we fuse 1-lenses, recalling that 1-lenses are themselves simply asymmetriclenses?If L and L ′ are 1-lenses, then LL ′ is also a ( + − = ) -lens, so fusion is an operation on asymmetriclenses. But it is not the usual composition of asymmetric lenses because fusable 1-lenses have commonichael Johnson &Robert Rosebrugh 103codomains. That is, they form a cospan of asymmetric lenses L : S / / A = A ′ o o S ′ : L ′ . So, how dowe fuse a cospan? Definition 7 tells us that we pull the two asymmetric lenses back along each other,and the resulting asymmetric lens is the diagonal of the “pullback” square T / / A . This is sometimesknown as the consistency lens . In database terms, if the trough of the cospan A is the system of statesof common data, then the peak of the “pullback” is, up to isomorphism, the category whose objects areconsistent pairs of states of the systems S and S ′ , consistent in as much as they share the same commondata state, and whose arrows are pairs of transitions, one from S and one from S ′ which are consistent inas much as they involve the same transition in A for the shared data. The 1-lens LL ′ is an asymmetriclens. The Get, the functor part of the diagonal, tells us how the shared data changes when a T transitiontakes place, and the Put tells us how to change the consistent states in T when the shared data is changed.But there is yet another way that we might fuse the asymmetric lenses L and L ′ . It is well-known thatan asymmetric lens can be represented as a symmetric lens in two ways: For the asymmetric lens L , forma span of asymmetric lenses (Definition 2) by pairing L with the identity on S on either the left of the right.If we do that on the left for L , and on the right for L ′ (using of course the identity on S ′ ) we obtain two2-lenses which we know are symmetric forms of the asymmetric lenses L and L ′ , and these two 2-lensesare again fusable. This time Definition 7 tells us that the resulting lens with be a ( + − = ) -lens:It is the three legged “pullback” cone over the cospan S / / A = A ′ o o S ′ consisting of the consistencylens in the middle, and the two “pullback” projection lenses H : T / / S and H ′ : T / / S ′ on the left andright.The last paragraph describes a special case of the fusion of two symmetric lenses: Two 2-lenses fuseto form a 3-lens. The three legs are again the consistency lens in the middle, and the outer two legs are,together, the usual symmetric lens composite. The fusion “remembers” the foot A that the symmetriclenses have been composed over, and its relationship to the peak T via the consistency lens. This is asmall, but important difference, as we will soon see. The fusion remembers the way the composed upsymmetric lens factors into two symmetric lenses. And why is this important? It is because, as notedin Section 5, the fact that there might be a cospan representation of each symmetric lens is important inengineering, but the composed symmetric lens might have no cospan representation so the factorisation isvital for actually building system interoperations. Let’s look again at the example presented in Section 2and further developed in Sections 3 and 5.Recall that there are symmetric lenses, 2-lenses, between ABC Frames and XYZ Warehouse, andbetween XYZ Warehouse and XYZ Logistics, and that those two symmetric lenses are cospan repre-sentable, but that the composite 2-lens between ABC Frames and XYZ Logistics is not cospan repre-sentable.If we are concerned, as was hypothesised in Section 5, with the interoperations between ABC Framesand XYZ Logistics, we might have composed the two symmetric lenses and lost the information that thecomposite factors into two symmetric lenses that are cospan representable. But alternatively, we couldhave fused the two symmetric lenses, the two 2-lenses, to obtain a 3-lens. That 3-lens does indeedcontain all the information required to study and prove properties about the interactions between ABCFrames and XYZ Logistics. But it also includes the base information to see how to factorise that in-teraction through XYZ Warehouse, and through that factorisation and the cospan representations, theinteroperations are then easy to engineer as well.Sometimes, lens fusions are better than lens compositions.Thus, the more legs the merrier: In our example in fact, if we have the cospans the best fusion is fivelegged! See below. But first, a little more about fusions.04 Themore legsthe merrier At first sight, some people find the fusion operator confronting because it works like a composition (atleast, one can only fuse composable lenses), but n -lenses, and especially concerningly the familiar 2-lenses normally called symmetric lenses, aren’t closed under fusion. In general, fusion takes things ofcertain types and produces things of different types.So it seems worthwhile to point out that operators like fusion are common, and have a long historyin mathematics and software engineering. To offer just a few examples:1. Path categories: Paths in a topological space X are normally defined to be continuous functionsfrom the unit interval [ , ] to X . Two paths with common end and start points can be composedby reparameterization to get a new path — the first path is traversed “twice as fast” so that thesecond path can be traversed in the second half of the unit interval. Probably this is all familiar.Of course, such composition is not associative because three paths will be traversed in either thefirst two quarters and the last half of the unit interval or the first half and the last two quarters ofthe unit interval depending on which composition is taken first. So, we introduce an equivalencerelation, homotopy, which allows reparameterized paths to be treated as equivalent.Alternatively, one might approach the problem in the style of fusion. Let paths be continuousfunctions from an interval of length n , say for non-negative integers n , and paths are fused (butusually still called “composed”) by having a path from [ , m ] and a path from [ , n ] form a pathfrom [ , m + m ] . This fusion is associative and has paths of length zero, paths from [ , ] , alsoknown as points, as identities. Such paths form a category, the Moore Path Category, with no needfor any equivalence relation.2. Free monoid construction (including list concatenation): The discrete form of the example justgiven is familiar to computer scientists. Lists, or indeed arrays, might be seen as functions fromsets [ n ] of n elements into a data type X . The concatenation of lists of length m and length n givesa list of length m + n by fusing the functions. In mathematics of course, this is the constructionof the free monoid on a set X via words in the alphabet X . Again associativity is immediate, andidentity comes from the empty domain [ ] .3. Other free constructions from F
1: In both the fusion examples just given, the collection of domainshas the form of a coalgebra family [18] and can be calculated from the free algebra on the terminal.There are more examples of the same kind.4. Composition of (lax) natural transformations: To offer an example of a rather different kind, nat-ural transformations are, in chain complex terms, degree 1 maps. Given a natural transformation η : F / / G : A / / B an object of A is sent to an arrow η A of B , and an arrow of A is sentto a commutative square in B , or if B is a 2-category and η a lax natural transformation, to a2 -cell of B , etc. The horizontal composite of natural transformations is normally said to yield anatural transformation because a commuting square is indeed a 1-cell. But a very natural compo-sition, in analogy with the examples above, one might say a fusion, of lax natural transformations,yields a modification (a degree 2 map), amd indeed the fusion of three lax natural transformationsyields a perturbation (a degree 3 map). And more generally degree m and degree n maps in highercategories can fuse to give degree m + n maps. An extensive study of algebras with these kindsof compositions was undertaken by the Dutch mathematician Sjoerd Crans under the name teisi (singular tas ).We end this section with a note about counting. Recall that the fusion of an m -lens and an n -lensis an ( m + n − ) -lens. But the examples just given “fuse” m -structures and n -structures to get ( m + n ) -ichael Johnson &Robert Rosebrugh 105structures. In fact there is no substantive difference, and the apparent difference arises just from how wecount. The natural way of counting, and hence of labelling, multilenses is by counting the legs. But theexamples above are counted and labelled instead by the equivalent of the spaces between the legs (theinterval [ , n ] for example is of length n because there are n unit intervals in the spaces between the “feet” { , , . . . n } ) . The formulas coincide exactly if we use the same counting paradigm in each case.A further example, and one in which the natural count again corresponds to the way we count legs in n -lenses, is the natural join operation for databases (this example was suggested to us by an anonymousreferee). To take it in its simple form, two tables in a database consisting of say m and n columnsrespectively, are joined on some common data (often a key attribute) to yield a table with m + n −
10 Conclusion and further work
We have seen that the fusion operation is sometimes better than the normal composition of, for example,symmetric lenses, because it preserves information about what structures have been composed over, andthis factorisation information may be very valuable in knowing where to find cospan representations.And those cospan representations may be very useful in the implementation of systems interoperations.But, the reader might ask, if we have those cospan representations, why would we even do fusion?We don’t want to lose the cospan representations if they’re so useful for implementations, and the cospanrepresentations are among the feet of the spans. The fusion preserves legs and feet, but nothing betweenthe feet. The results of fusions are wide spans: A peak, some legs, and some (bare) feet.In further work we have shown that this loss of the cospans need not be an issue at all.If we have the cospan representations, then we begin with a “zig-zag“ of asymmetric lenses amongthe feet. As discussed in Section 8 we can treat each of those asymmetric lenses as a symmetric lens,a 2-lens, (by pairing it, on the outside of the cospan, with identities) and then fuse the 2-lenses so thateach cospan becomes a 3-lens. We can even do all this in one go — and this is a general result — andthe fusion will be a wide span of asymmetric lenses canonically built on the limit cone of the zig-zag ascalculated in cat .In the case of our supply chain example, the previous paragraph means that we end up with a 5-lens.The five legs are asymmetric lenses with codomains the three business systems (ABC Frames, XYZWarehouse and XYZ Logistics) and the two common data subsystems ( X and Orders / / XYX ). Asnoted above, the cospans among the feet are indeed gone, but their objects remain, and, remarkably, thecospans can be uniquely recovered whenever required. This follows from a particularly nice orthogonalfactorisation system on
ALens using image factorisations. And image factorisations are much simplerfor lenses than for arbitrary functors, and are frequently used, often tacitly, by engineers who cut lensesdown to their image factorisations routinely. The unique fillers for the orthogonal factorisation systemrestore the asymmetric lenses making up the cospans whenever they are required. The fusion containsnot just the factorisation information required to search for the cospan representations, but in fact all theinformation needed to fully determine the cospan representations, and so all the information needed foran effective implementation.
11 Acknowledgements
The authors gratefully acknowledge the support of the Australian Research Council, the Centre of Aus-tralian Category Theory and Mount Allison University. We have benefited from the perspicacious com-06 Themore legsthe merrierments of anonymous referees and from useful discussions with Bryce Clarke and Angus Johnson, andwe thank them all for sharing their insights.
References [1] Aguiar, M. (1997)
Internal Categories and Quantum Groups . Ph.D. thesis, Cornell University.[2] Bancilhon, F. and Spyratos, N. (1981) Update semantics of relational views.
ACM Transactions on DatabaseSystems , 557–575. doi:10.1145/319628.319634[3] Clarke, B. (2019) Internal lenses as functors and cofunctors. Electronic Proceedings in Theoretical ComputerScience , , 183–195. doi:10.4204/EPTCS.323.13[4] Clarke, B. (2020) A diagrammatic approach to symmetric lenses. Electronic Proceedings in TheoreticalComputer Science , to appear, 13pp.[5] Dampney, C.N.G and Johnson, M. (2001) Half-duplex interoperations for cooperating information systems.
Advances in Concurrent Engineering , 565–571. IN-1, (International Institute of Concurrent Engineering,ISBN 09710461-0-7, 2000).[6] Diskin, Z., K¨onig, H., and Lawford, M. (2018) Multiple model synchronization with multiary delta lenses,
Lecture Notes in Computer Science , 21–37. doi:10.1007/978-3-319-89363-1 2[7] Diskin, Z., Xiong, Y., and Czarnecki, K. (2011) From State- to Delta-Based Bidirectional Model Transfor-mations: the Asymmetric Case.
Journal of Object Technology , 1–25. doi:10.5381/jot.2011.10.1.a6[8] Diskin, Z., Xiong, Y., Czarnecki, K., Ehrig, H., Hermann, F., and Orejas, F. (2011) From State- to Delta-Based Bidirectional Model Transformations: the Symmetric Case. Lecture Notes in Computer Science ,304–318. doi:10.1007/978-3-642-24485-8 22[9] Diskin, Z. and Maibaum, T. (2012) Category Theory and Model-Driven Engineering: From Formal Seman-tics to Design Patterns and Beyond, 7th ACCAT Workshop on Applied and Computational Category Theory,
Electronic Proceedings in Theoretical Computer Science , , 1–21. doi:10.4204/EPTCS.93.1[10] Gibbons, J. and Stevens, P. (2016) Bidirectional Transformations. Lecture Notes in Computer Science .doi:10.1007/978-3-319-79108-1[11] Hofmann, M., Pierce, B., and Wagner, D. (2011) Symmetric Lenses. In ACM SIGPLAN-SIGACTSymposium on Principles of Programming Languages (POPL),
ACM SIGPLAN Notices , 371–384.doi:10.1145/1925844.1926428[12] Johnson, M. and Rosebrugh, R. (2007) Fibrations and universal view updatability. Theoretical ComputerScience , 109–129. doi:10.1016/j.tcs.2007.06.004[13] Johnson, M. and Rosebrugh, R. (2016) Unifying set-based, delta-based and edit-based lenses. Proceedingsof the 5th International Workshop on Bidirectional Transformations, Eindhoven
CEUR Proceedings ,1–13.[14] Johnson, M. and Rosebrugh, R. (2017) Symmetric delta lenses and spans of asymmetric delta lenses.
Journalof Object Technology , , 2:1–32. doi:10.5381/jot.2017.16.1.a2[15] Johnson, M. and Rosebrugh, R. (2018) Cospans and symmetric lenses. Programming 18 Companion , ACM,21–29. doi:10.1145/3191697.3191717[16] Johnson, M. and Rosebrugh, R. (2019) Multicategories of multiary lenses.
CEUR Proceedings , 30–44.[17] Johnson, M. and Stevens, P. (2018) Confidentiality in the process of (model driven) software development.
Programming 18 Companion , ACM, 1–8. doi:10.1145/3191697.3191714[18] Johnson, M. and Walters, R.F.C. (1992) Algebra objects and algebra families for finite limit theories.
Journalof Pure and Applied Algebra , , 283–293.[19] Leinster, T. (2004) Higher Operads, Higher Categories . Cambridge University Press. arXiv:math/0305049doi:10.1017/CBO9780511525896 ichael Johnson &Robert Rosebrugh 107 [20] Oles, F. J. (1982)