Extensional equality preservation and verified generic programming

In verified generic programming, one cannot exploit the structure of concrete data types but has to rely on well chosen sets of specifications or abstract data types (ADTs). Functors and monads are at the core of many applications of functional programming. This raises the question of what useful ADTs for verified functors and monads could look like. The functorial map of many important monads preserves extensional equality. For instance, if $f, g : A \rightarrow B$ are extensionally equal, that is, $\forall x \in A, \ f \ x = g \ x$, then $map \ f : List \ A \rightarrow List \ B$ and $map \ g$ are also extensionally equal. This suggests that preservation of extensional equality could be a useful principle in verified generic programming. We explore this possibility with a minimalist approach: we deal with (the lack of) extensional equality in Martin-L\"of's intensional type theories without extending the theories or using full-fledged setoids. Perhaps surprisingly, this minimal approach turns out to be extremely useful. It allows one to derive simple generic proofs of monadic laws but also verified, generic results in dynamical systems and control theory. In turn, these results avoid tedious code duplication and ad-hoc proofs. Thus, our work is a contribution towards pragmatic, verified generic programming.


Introduction
This paper is about extensional equality preservation in dependently typed languages like Idris (Brady, 2017), Agda (Norell, 2007) and Coq (The Coq Development Team, 2021) that implement Martin-Löf's intensional type theory (Martin-Löf & Sambin, 1984). We discuss Idris code but the results could be translated to other languages. Extensional equality is a property of functions, stating that they are "pointwise equal": Different flavours of equality. "All animals are equal, but some animals are more equal than others" [Animal Farm, Orwell (1946)] There are several kinds of "equality" relevant for programming. Programming languages usually offer a Boolean equality check operator and in Idris it is written ( ), has type {A : Type} → Eq A ⇒ A → A → Bool and is packaged in the interface Eq. This is an "adhoc" equality, computing whatever the programmer supplies as an implementation. This paper is not about value level Boolean equality.
On the type level, the dependently typed languages we consider in this paper provide a notion of intensional equality, also referred to as an "equality type", which is an inductively defined family of types, usually written infix: (a = b) : Type for a : A and b : B. It has just one constructor Refl : a = a. The resulting notion is not as boring as it may look at first. We have Refl : a = b not only if a and b are identical, but also if they reduce to identical expressions. Builtin reduction rules normally include alpha-conversion (capturefree renaming of bound variables), beta-reduction (using substitution) and eta-reduction: f = λ x ⇒ f x. So, for example, we have Refl : id x = x. Furthermore, user-defined equations are also used for reduction. A typical example is addition of natural numbers: with + defined by pattern matching on the first argument, we have e.g. Refl : 1 + 1 = 2. However, while for a variable n : N we have Refl : 0 + n = n, we do not have Refl : n + 0 = n.
One very useful property of intensional equality is that it is a congruence with respect to any function. In other words, all functions preserve intensional equality. The proof uses pattern matching, which is straightforward here because Refl is the only constructor: In a similar way, one can prove that (=) is an equivalence relation: reflexivity is directly implemented by Refl, while symmetry and transitivity can be proven by pattern matching.
Extensional equality. As one would expect, extensional equality is an equivalence relation In general, we can lift any (type-valued) binary relation on a type B to a binary relation on function types with co-domain B. The extify combinator maps equivalence relations to equivalence relations. Using it we can redefine ( . =) = extify (=) and we can easily continue to quantify over more arguments: ( .. =) = extify ( . =), etc. In this paper our main focus is equality on functions, and we will explore in some detail the relationship between f = g and f . = g. In Martin-Löf's intensional type theory, and thus in Idris, extensional equality is strictly weaker than intensional equality. More concretely, we can implement = g IEqImplEE f f Refl = λ x ⇒ Refl but not the converse, normally referred to as function extensionality: When working with functions, extensional equality is often the notion of interest and libraries of formalized mathematics typically provide definitions like . = and basic results like IEqImplEE. See for example homot and eqtohomot in Part A of the UniMath library (Voevodsky et al., 2021) or eqfun in Coq (The Coq Development Team, 2021).
In reasoning about generic programs in the style of the Algebra of Programming (Bird & de Moor, 1997;Mu et al., 2009) and, more generally, in pen and paper proofs, the principle of function extensionality is often taken for granted.
EE preservation. Preservation of extensional equality is a property of higher order functions: we say that, for fixed, non-function types A, B, C and D, a function h : (A → B) → (C → D) preserves extensional equality (in one argument) if f . = g implies h f . = h g. Higher order functions are a distinguished trait of functional programming languages (Bird, 2014) and many well known function combinators can be shown to preserve extensional equality. In particular, the arrow-function map for Identity, List, Maybe and for many other polymorphic data types preserves extensional equality. The standard libraries of Agda and Coq provide several instances 1 2 .
Similarly, if h takes two function arguments it preserves extensional equality (in two arguments) if f 1 .
= g 1 and f 2 . = g 2 implies h f 1 f 2 . = h g 1 g 2 , etc. To illustrate the Idris notation for equational reasoning we show the lemma compPresEE proving that function composition satisfies the two-argument version of extensional equality preservation: The right hand side is a chain of equal expressions connected by the ={ proofs }= of the individual steps within special braces and ending in QED, see "Preorder reasoning" in the documentation by The Idris Community (2020). The steps with Refl are just for human readability, they could be omitted as far as Idris is concerned. Note that the proof steps are at the level of intensional equality which all functions preserve as witnessed by cong. So one can often use cong in steps where an outer context is unchanged (like g in this example). A special case of a two-argument version of cong shows that composition (like all functions) preserves intensional equality: Note that the "strengths" of the two equality preservation lemmas are not comparable: compPresIE proves a stronger conclusion, but from stronger assumptions.
ADTs and equality preservation. Abstract data types are often specified (e.g., via Idris interfaces or Agda records) in terms of higher order functions. Typical examples are, beside the already mentioned map for functors, bind and Kleisli composition (see section 2) for monads. This paper is also about ADTs and generic programming. More specifically, we show how to exploit the notion of extensional equality preservation to inform the design of ADTs for generic programming and embedded domain-specific languages (DSLs). This is exemplified in sections 3 and 4 with ADTs for functors and monads but we conjecture that other abstract data types, e.g. for applicatives and arrows, could also profit from a design informed by the notion of preservation of extensional equality.
Thus, our work can also be seen as a contribution to the discussion on verified ADTs initiated by Nicholas Drozd on idris-lang. A caveat is perhaps in place: the discussion on ADTs for functors and monads in sections 3 and 4 is not meant to answer the question of "what verified interfaces should look like". Our aim is to demonstrate that, like preservation of identity functions or preservation of composition, preservation of extensional equality is a useful principle for ADT design.
What this paper is not about. Before turning to a first example, let us spend a few words on what this paper is not about. It is not intended as a contribution to the theoretical study of the equality type in intensional type theory or the algorithmic content of the function extensionality principle.
The equality type in intensional type theory and the question of how to deal with extensional concepts in this context has been the subject of important research for the last thirty years. Since Hofmann's seminal work (Hofmann, 1995), setoids have been the established, but also often dreaded (who coined the expression "setoid hell"?) means to deal with extensional concepts in intensional type theory (see also section 6). Eventually, the study of Martin-Löf's equality type has lead to the development of Homotopy Type Theory and Voevodsky's Univalent Foundations program (Streicher, 1991;Hofmann & Streicher, 1994;The Univalent Foundations Program, 2013). Univalence and recent developments in Cubical Type Theory (Cohen et al., 2018) promise to finally provide developers with a computational version of function extensionality. This paper is a contribution towards pragmatic verified generic programming. From this perspective, it might become obsolete when fully computational notions of function extensionality will become available in mainstream programming. From a more mathematical perspective, there are good reasons not to rely on axioms that are stronger than necessary: there are interesting models of type theory that refute function extensionality (Streicher, 1993;von Glehn, 2015;Boulier et al., 2017), and our results can be interpreted in these models.
The paper has been generated from literate Idris files. These can be type-checked with Idris 1.3.2 and are available at https://gitlab.pik-potsdam.de/botta/papers.

Equality examples from dynamical systems theory
In dynamical systems theory (Kuznetsov, 1998;Thomas & Arnol'd, 2012), a prominent notion is that of the flow (or iteration) of a system. We start by discussing deterministic systems and then generalize to the monadic case. A deterministic dynamical system on a set X is an endofunction on X. The set X is often called the state space of the system. Given a deterministic system f : X → X, its n-th iterate or flow, is typically denoted by f n : X → X and is defined by induction on n: the base case f 0 = id is the identity function and f n+1 is defined to be either f • f n or f n • f . The two definitions are mathematically equivalent because of associativity of function composition but what can one prove about f • f n and f n • f in intensional type theory? We define the two variants as flowL and flowR: For readability, we spell out the proof sketch for the induction step in full: First, we apply the definition of flowL to deduce flowL f (S n) = flowL f n • f . Next, we apply compPresIE with the induction hypothesis flowLemma f n and deduce flowL f n • f = flowR f n • f . The (almost) final step is to show that flowR f n • f = f • flowR f n. This is obtained via the auxiliary flowRLemma where we use associativity and preservation of intensional equality again.
Let's summarize: we have considered the special case of deterministic dynamical systems, defined the flow (a higher order function) in two different ways and shown that the two definitions are equivalent in the sense that e 1 = flowR f n and e 2 = flowL f n are intensionally equal for all f and n. Before we move on to a more general setting, where intensional equality does not hold, let's expand a bit on the different levels of equality relevant for these two functions. The two expressions e 1 and e 2 denote functions of type X → X and thus for any x : X we also have e 1 x = e 2 x. On the other hand, the quantification over all n can be absorbed into the definition of extensional equality so that we have flowR f . = flowL f for all f . And with the two-argument version of extensional equality we get flowR ..

= flowL.
Monadic systems. What about non-deterministic systems, stochastic systems or perhaps fuzzy systems? Can we extend our results to the general case of monadic dynamical systems? Monadic dynamical systems (Ionescu, 2009) on a set X are functions of type X → M X where M is a monad. When M is the identity monad, one recovers the deterministic case. When M is List one has non-deterministic systems, and finite probability monads capture the notion of stochastic systems.
One can extend the flow (and, as we will see in section 5, other elementary operations) of deterministic systems to the general, monadic case by replacing id with pure and function composition with Kleisli composition (> = >): Notice, however, that now the implementations of flowMonL and flowMonR depend on (> = >), which is a monad-specific operation. This means that, in proving properties of the flow of monadic systems, we can no longer rely on a specific definition of (> = >): we have to derive our proofs on the basis of properties that we know (or require) (> = >) to fulfilthat is, on its specification.
What do we know about Kleisli composition in general? We discuss this question in the next two sections but let us anticipate that, if we require functors to preserve the extensional equality of arrows (in addition to identity and composition) and Kleisli composition to fulfil the specification then we can derive preservation of extensional equality and associativity of Kleisli composition generically.
From these premises, we can prove the extensional equality of flowMonL and flowMonR using a similar lemma as in the deterministic case: First, notice that the base case of the lemma requires computing evidence that pure > = > f is extensionally equal to f > = > pure. This is a consequence of pure being a left and a right identity for Kleisli composition: for f : As we will see in subsection 4.1, pureLeftIdKleisli and pureRightIdKleisli are either ADT axioms or theorems, depending of the formulation of the monad ADT. The induction step of flowMonRLem relies on preservation of extensional equality and on associativity of Kleisli composition: Finally, the extensional equality of flowMonL and flowMonR flowMonLemma : follows from flowMonRLem and, again, preservation of extensional equality.
Discussion. Before we turn to the next section, let us discuss one objection to what we have just done. Why have we not tried to prove that flowMonL f n and flowMonR f n are intensionally equal as we did for the deterministic flows? If we managed to show the intensional equality of the two flow computations, their extensional equality would follow.
The problem with that approach is that it would require much stronger assumptions: pureLeftIdKleisli, pureRightIdKleisli, kleisliAssoc and kleisliSpec would need to hold intensionally. For example, it would require f > = > g to be intensionally equal to join • map g • f . In section 4 we will see that, in some abstract data types for monads this is indeed the case, but to require all of these would make our monad interface impossible (or at least very hard) to implement. In general, we cannot rely on f > = > g to be intensionally equal to join • map g • f .
In designing ADTs and formulating generic results, we have to be careful not to impose too strong proof obligations on implementors. Requiring the monad operations to fulfil intensional equalities would perhaps not be as bad as pretending that function extensionality holds in general, but would still imply unnecessary restrictions. By contrast, requiring proper functors to preserve the extensional equality of arrows is a natural, minimal invasive specification: it allows one to leverage on what List, Maybe, Dist (Erwig & Kollmansberger, 2006), SimpleProb (Botta et al., 2017) and many other monads that are relevant for applications are known to fulfil, derive generic verified implementations, avoid boilerplate code and improve the understandability of proofs.

Functors and extensional equality preservation
In category theory, a functor F is a structure-preserving mapping between two categories C and D. A functor is both a total function from the objects of C to the objects of D and a total function from the arrows of C to the arrows of D (often both denoted by F) such that for each arrow f : For an introduction to category theory, see Pierce (1991). The arrow map preserves identity arrows and arrow composition. In formulas: Here A denotes an object of C , F A the corresponding object of D under F, id A and id F A denote the identity arrows of A and F A in C and D, respectively and g and f denote arrows between suitable objects in C . In D, F id A , F (g • f ), F g and F f denote the arrows corresponding to the C -arrows id A , g • f , g and f .
Level of formalization. When considering ADT specifications of functor (and of natural transformation, monad, etc.) in dependently typed languages, one has to distinguish between two related but different situations. One in which the specification is put forward in the context of formalizations of category theory, see for example (Voevodsky et al., 2021;The Coq Development Team, 2021). In this situation, one has to expect the notion of category to be in place and that of functor to be predicated on that of its source and target categories. A functor ADT in this situation is an answer to the question "What shall the notion of functor look like in dependently typed formalizations of category theory?" A different situation is the one in which, in a dependently typed language, we consider the category whose objects are types (in Idris, values of type Type), arrows are functions, and functors are of type Type → Type. In this case, a functor ADT is an answer to the question "What does it mean for a value of type Type → Type to be a functor?" and category theory plays the role of a meta-theory that we use to motivate the specification.
The latter situation is the one considered in this paper. More specifically, we consider the ADTs encoded in the Haskell type classes Functor and Monad and ask ourselves what are meaningful specifications for these ADTs in dependently typed languages.
Towards an ADT for functors. In Idris, the notion of a functor that preserves identity and composition can be specified as follows (but this is not our final version): In mapPresId we have to help the type checker a little bit and give the domain of the two functions that are posited to be extensionally equal explicitly. Notice that the function map is required to preserve identity and composition extensionally. In other words, Functor does not require map id and id (map (g • f ) and map g • map f ) to be intensionally equal but only to be equal extensionally. This is for very good reasons! If functors were required to preserve identity and composition intensionally, the interface would be hardly implementable. By contrast, Identity, List, Maybe, Vect n and many other important type constructors are functors in the sense specified by this Functor interface.
Does this Functor interface represent a suitable Idris implementation of the notion of functor in dependently typed languages? We argue that this is not the case and that beside requiring from map preservation of identity and of composition, one should additionally require preservation of extensional equality. In other words, we argue that the above specification of Functor is incomplete. A more complete specification could look like The Identity functor, List, Maybe, Vect n and, more generally, container-like functors built from algebraic datatypes, fulfil the complete specification and the proofs for mapPresEE do not add significant work. But other prominent functors such as Reader do not fulfil the above specification as we will explain below. Note that it is quite possible to continue on the road towards full generality (supporting a larger class of functors) by parameterising over the equalities used, but this leads to quite a bit of book-keeping (basically a setoid-based framework). We instead stop at this point and show that it is a pragmatic compromise between generality and convenient usage.
Equality preservation examples. Let's first have a look at map and a proof of mapPresEE for List, one of the functors that fulfil the above specification: [ ] mapList f (a :: as) = f a :: mapList f as Written out in equational reasoning style, the preservation of EE proof looks as follows: = Refl mapListPresEE f g fEEg (a :: as) = (mapList f (a :: as)) ={ Refl }= (f a :: mapList f as) ={ cong {f = (:: mapList f as)} (fEEg a) }= (g a :: mapList f as) ={ cong (mapListPresEE f g fEEg as) }= (g a :: mapList g as) ={ Refl }= (mapList g (a :: as)) QED In general the proofs have a very simple structure: they use the f . = g arguments at the "leaves", and otherwise only use the induction hypotheses. With a suitable universe of codes for types, or a library for parametricity proofs, these proofs can be automated using datatype-generic programming.
Let's now turn to a type constructor that is not an instance of our Functor, namely Reader E for some environment E : Type.
If we try to implement preservation of extensional equality we end up with Notice the question mark in front of whatnow. This introduces an unresolved proof step and allows us to ask Idris to help us implementing this step, see "Elaborator Reflection -Holes" in (The Idris Community, 2020). Among other things, we can ask about the type of whatnow. Perhaps not surprisingly, this turns out to be f • r = g • r.
The problem is that, although we know that (f • r) e = (g • r) e for all e : E, we cannot deduce f • r = g • r without extensionality. Thus Reader E does not implement the Functor interface, but it is "very close". Using the 2-argument version of function extensionality = mapR g mapRPresEE2 f g fEEg r x = fEEg (r x) Thus, Reader E is an example of a functor which does not preserve, but rather transforms the notion of equality. By a similar argument, mapPresEE does not hold for the continuation monad.
As we mentioned earlier, it is tempting to start adding equalities to the interface (towards a setoid-based framework), but this is not a path we take here. As a small hint of the problems the setoid path leads to, consider that we already have four different objects (A, B, F A, F B) and two arrow types (A → B, F A → F B), all of which could be allowed "their own" notion of equality.
Wrapping up. As stated in section 1, we argue that, for verified generic programming, it is useful to distinguish between type constructors whose map can be shown to preserve extensional equality and type constructors for which this is not the case. A discussion of what are appropriate names for the respective ADTs is beyond the scope of this paper. In the next section we explore how functors with mapPresEE affect the monad ADT design.

Verified monad interfaces
In this section, we review two standard notions of monads. We discuss their mathematical equivalence and consider "thin" and "fat" monad ADT formulations. We discuss the role of extensional equality preservation for deriving monad laws and for verifying the equivalence between the different ADT formulations. There are many possible ways of formulating Monad axioms. Here, we do not argue for or against a specific formulation but rather discuss the most popular ones and their trade-offs.

The traditional view
In category theory, a monad is an endofunctor M on a category C together with two natural transformations η : Id − → M (the multiplication) such that, for any object A of C , the following diagrams commute: The transformations η and µ are families of arrows, one for each object A, with types η A : A → M A and µ A : M (M A) → M A. That they are natural transformations means that the following diagrams commute for any arrow f : A → B in C : From this perspective, a monad is a functor with additional structure, namely families of maps η and µ, satisfying, for any arrow f : A → B, the five properties: In functional programming, η is traditionally denoted by return or by pure and µ is traditionally called join. Idris provides language support for interface refinement. Thus, we can leverage on the functor ADT Functor from section 3 and define a monad to be a functor with additional methods pure and join that satisfy the requirements T1-T5: Kleisli composition in the traditional view. In section 2, we have seen that monads are equipped with a (Kleisli) composition (> = >) that we required to fulfil kleisliSpec: One way of implementing (> = >) that satisfies kleisliSpec is to define The extensional equality between f > = > g and join • map g • f then follows directly: The same approach can be followed for implementing bind, another monad combinator similar to Kleisli composition: Starting from a thin monad ADT as in the example above and adding monadic operators that fulfil a specification by-construction, is a viable approach. It leads to a rich structure entailing monad laws that can be implemented generically. Thus, one can show that pure is a left and a right identity of Kleisli composition (we show only one side here) ={ Refl }= (join (map f (pure a))) ={ cong {f = join} (pureNatTrans f a) }= (join (pure (f a))) ={ triangleLeft (f a) }= (f a) QED and that Kleisli composition is associative as stated in section 2, almost straightforwardly and without having to invoke the mapPresEE axiom of the underlying functor.
Notice that in order to show that Kleisli composition preserves extensional equality, one has to rely on the mapPresEE axiom of the underlying functor, as one would expect.
In the implementation of kleisliPresEE, we have applied the "leapfrogging" rule (compare (Bird, 2014), p. 250): Fat ADTs. The main advantages of the approach outlined above -a thin ADT and explicit definitions of the monadic combinators -are readability and straightforwardness of proofs: thanks to the intensional equality between f > = > g and join • map g • f , we were able to implement many proof steps with just Refl.
The strength of thin ADT designs is also their weakness: in many practical cases, one would like to be able to define join in terms of bind and not the other way round. In other words, one would like to weaken the requirements on, e.g., join, map and Kleisli composition and just require that f > = > g and join • map g • f are extensionally equal. If they happen to be intensionally equal for a specific instance, the better.
This suggests that an alternative way of formalizing the traditional notion of monads from category theory could be through a fat ADT: Type} One could go even further and add more combinators (and their axioms) to the ADT, but for the purpose of this discussion the above example will do. (In any case, many of these methods could be filled in by defaults.) What are the implications of having replaced definitions with specifications? A direct implication is that now, in implementing generic proofs of the monad laws, we have to replace some Refl steps with suitable specifications. Thus, for instance pureLeftIdKleisli becomes where we have replaced the first proof step, Refl, with kleisliJoinMapSpec pure f a. Similar transformations have to be done for pureRightIdKleisli, kleisliAssoc, etc. However, completing the proof of the monad laws for the fat interface is not just a matter of replacing definitions with specifications. Consider associativity: Here, in order to deduce (f > = > (g > = > h)) a from (f > = > (join • map h • g)) a in the last step of the proof, we had to apply instead of just Refl as in the case of thin interfaces. In other words: the specification kleisliJoinMapSpec alone is not strong enough to grant the last step. It allows one to deduce that join • map h • g and g > = > h are extensionally equal. But this is not enough: we need a proof that Kleisli composition preserves extensional equality. This relies on the functorial map of M preserving extensional equality, as in the case of thin ADTs. The moral is that, when the relationships between the monadic operations pure, join and (> = >) are specified rather then defined, preservation of extensional equality plays a crucial role even in proofs of straightforward properties like associativity. The same situation occurs if we specify bind in terms of pure and join.

The Wadler view
A different perspective on monads goes back to (Manes, 1976) and has been popularized by P. Wadler (1992): a monad on a category C can be defined by giving an endofunction M on the objects of C , a family of arrows η A : A → M A (like η above, but not required to be natural), and a "lifting" operation that maps any arrow f : A → M B to an arrow f * : M A → M B. The lifting operation is required to satisfy W1-W3 for any objects A, B, C and arrows f : A → M B and g : B → M C, see (Streicher, 2003): From tradition to Wadler and back. The two monad definitions can be seen as two views on the same mathematical concept and we would like the corresponding ADT formulations to preserve this relationship.
It turns out that, if (M, η, µ) fulfil the properties T1-T5 of the traditional view, then the object part of M, η, and the lifting operation defined by f * = µ M B • map f satisfy W1-W3.
In turn, given M, η and · * that satisfy W1-W3, one can define map f = (η B • f ) * and µ A = id * M A and prove that (M, map) is a functor, and that T1-T5 are all satisfied. This economical way to define a monad has become very popular in functional programming, where lift f = f * is usually given in infix form with flipped arguments and called bind: ma > > = f = f * ma. This suggests yet another ADT for monads: The three axioms are formulations of the properties of lift W1-W3 in terms of bind. We can now define map, join and Kleisli composition in terms of bind and pure: The obligation is now to prove that pure and join fulfil the properties T1-T5, for instance, that pure is a natural transformation. In much the same way as for formalizations of the traditional view, some of these proofs can be implemented straightforwardly. But in some cases, one runs into trouble. Consider the proof of T2. Triangle right: We know that λ a ⇒ pure a > > = id and id are extensionally equal by pureLeftIdBind id. If this equality would hold intensionally, we could fill the hole by congruence. But we cannot strengthen ( . =) to (=) in pureLeftIdBind. Instead, we extend our ADT with and complete the proof by filling in ?whatnow by: Notice that, in this approach, map is defined in terms of pure and bind. Thus, we do not have at our disposal the axioms of the functor ADT and thus we cannot leverage mapPresEE to derive liftPresEE as we have done in the traditional formulation for Kleisli composition. The moral is that, even if we adopt the Wadler view on monads and a more economical specification, we have to require lift to preserve extensional equality if we want our specification to be consistent with the traditional one. This completes the discussion on different notions of monads and on the role of extensional equality preservation in generic proofs of monad laws. For the rest of the paper, we apply the traditional view on monads and the fat monad interface.

More monad properties
As we have seen in section 2 for flowMonLemma, extensional equality preservation is crucially needed in inductive proofs. We discuss more examples of applications of the principle in the context of DSLs for dynamical systems theory in section 5. In the rest of this section, we prepare by deriving two intermediate properties. The first is the extensional equality between map f • join • map g and join • map (map f • g): The second, can be seen as an associativity law by rewriting it in terms of (< = <) = flip (> = >):

Applications in dynamical systems and control theory
In this section we discuss applications of the principle of preservation of extensional equality to dynamical systems and control theory. We have seen in section 2 that time discrete deterministic dynamical systems on a set X are functions of type X → X DetSys : Type → Type DetSys X = X → X and that generalizing this notion to systems with uncertainties leads to monadic systems where M is an uncertainty monad: List, Maybe, Dist (Erwig & Kollmansberger, 2006), SimpleProb (Ionescu, 2009;Botta et al., 2017), etc. For monadic systems, one can derive a number of general results. One is that every deterministic system can be embedded in a monadic system: We prove flowLemma2 by induction on m using the properties from section 4: pure is a left and right identity of Kleisli composition and Kleisli composition is associative. The base case is straightforward but the induction step again relies on Kleisli composition preserving extensional equality.
As seen in section 4, this follows directly from the monad ADT and from the preservation of extensional equality for functors.
A representation theorem. Another important result for monadic systems is a representation theorem: As for flowLemma2, proving the representation lemma is straightforward but crucially relies on associativity of Kleisli composition and thus, as seen in section 4, on preservation of extensional equality: Notice also the application of kleisliLeapfrog to deduce If we had formulated the theory in terms of bind instead of Kleisli composition, the two expressions would have been intensionally equal.
Flows and trajectories. Our last application of preservation of extensional equality in the context of dynamical systems theory is a result about flows and trajectories. For a monadic system f , the trajectories of length n + 1 starting at state x : X are In words, the trajectory obtained by making zero steps starting at x is an M-structure containing just [x]. To compute the trajectories for S n steps, we first bind the outcome of a single step f x : M X into trj f n. This results in an M-structure of vectors of length n. Finally, we prepend these possible trajectories with the initial state x.
Since trj f n x is an M-structure of vectors of states, we can compute the last state of each trajectory. It turns out that this is point-wise equal to flow f n: where lastLemma x : last • (x::) . = last. In the implementation of mapLastLemma we have applied both preservation of composition and preservation of extensional equality. With mapLastLemma in place, flowTrjLemma is readily implemented by induction on the number of steps (pure (last (x :: Nil))) ={ sym (pureNatTrans last (x :: Nil)) }= (map last (pure (x :: Nil))) ={ cong {f = map last } (sym (pureNatTrans {A = Vect Z X } (x::) Nil)) }= (map last (map (x::) (pure Nil))) ={ Refl }= Again, preservation of extensional equality proves essential for the induction step.
Dynamic programming (DP). The relationship between the flow and the trajectory of a monadic dynamical system also plays a crucial role in the semantic verification of dynamic programming. DP (Bellman, 1957) is a method for solving sequential decision problems. These problems are at the core of many applications in economics, logistics and computer science and are, in principle, well understood (Bellman, 1957;De Moor, 1995;Gnesi et al., 1981;Botta et al., 2017).
Proving that dynamic programming is semantically correct boils down to showing that the value function val that is at the core of the backwards induction algorithm of DP is extensionally equal to a specification val ′ .
The val function of DP takes n policies or decision rules and is computed by iterating n times a monadic dynamical system similar to the function argument of flow but with an additional control argument. At each iteration, a reward function is mapped on the states and the result is reduced with a measure function. In this computation, the measure function is applied a number of times that is exponential in n.
By contrast, val ′ is computed by applying the measure function only once, but to a structure of a size exponential in n that is obtained by adding up the rewards along all the trajectories.
The equivalence between val and val ′ is established by structural induction. As in the flowTrjLemma discussed above, map preserving extensional equality turns out to be pivotal in applying the induction hypothesis, see Brede & Botta (2021) for details.

Related work
As already mentioned in section 1, there is a large body of literature that relates in some form to (the treatment of) equality in intensional type theory. Most of that work, however, is concerned with the theoretical study of the Martin-Löf identity type or with the implementation of variants of type theory and thus very different in nature from the present paper which takes a pragmatic user-level approach.
Closest to our approach from the theoretical point of view are perhaps works on formalization in type theory using setoids. These were originally introduced by Bishop (Bishop, 1967) for his development of constructive mathematics, and studied in (Hofmann, 1995) for the treatment of weaker notions of equality in intensional type theory. Setoids are sets equipped with an equivalence relation and mappings between setoids have to take equivalent arguments to equivalent results. The focus of our paper can thus be seen as one special case with extensional equality of functions as the equivalence relation of interest and thus its preservation as coherence condition on mappings. The price to pay when using a fullfledged setoid approach is the presence of a potentially huge amount of additional proof obligations, needed to coherently deal with sets (types) and their equivalence relationsthis often is pointedly referred to as setoid hell (for instance in Altenkirch (2017), but it seems to have been used colloquially in the community for much longer).
Still, there are some large developments using setoids, e.g. the CoRN library (formalizing constructive mathematics) by Spitters & Semeria (2017) and the CoLoR library (for rewriting and termination) by Blanqui et al. (2020) in Coq where the proof assistant provides the user with some convenient tools for dealing with setoids (Sozeau, 2010). Setoids are also used in a number of formalizations of category theory, e.g. (Huet & Saïbi, 2000;Megacz, 2011;Wiegley, 2018;. Homotopy Type Theory with univalence (The Univalent Foundations Program, 2013) provides function extensionality as a byproduct. However, in most languages (notably in Coq in which the Univalent Foundations library (Voevodsky et al., 2021, UniMath) is developed), univalence is still an axiom and thus blocks computation. Moreover, univalence is incompatible with the principle of Uniqueness of Identity Proofs which e.g. in Idris is built in, and in Agda has to be disabled using a special flag.
Finally, in Cubical Type Theory (Cohen et al., 2018) function extensionality is provable because of the presence of the interval primitive and thus has computational content. Cubical type theory has recently been implemented as a special version of Agda (Vezzosi et al., 2021). Another (similar) version of homotopy type theory is implemented in the theorem prover Arend (JetBrains Research, 2021). However, it is not clear at the present stage how long it will take for these advances in type theory to become available in mainstream functional programming.
On the topic of interfaces (type classes) and their laws there is related work in specifying (Jansson & Jeuring, 2002), rewriting (Peyton Jones et al., 2001), testing (Jeuring et al., 2012) and proving (Arvidsson et al., 2019) type class laws in Haskell. The equality challenges here are often related to the semantics of non-termination as described in the Fast and Loose Reasoning paper (Danielsson et al., 2006). In a dependently typed setting there is related work on contrasting the power of testing and proving, including Agda code for the Functor interface with extensional equality for the identity and composition preservation but not preservation of extensional equality (Ionescu & Jansson, 2013). Carette et al. (2014) nicely abstract the ideas about different (minimal) interfaces that we only exemplified using verified monads. Regarding the relation between different representations of monads, the reader might contrast the approach in the UniMath (Voevodsky et al., 2021, CategoryTheory.Monads.KTriplesEquiv) library with our approach in section 4. The UniMath development is part of a full-fledged formalization of category theory and relates "the traditional view" with the "Wadler view" of a monad (as we called them) via a weak equivalence of categories. This approach is very satisfactory from an abstract mathematical perspective. Our equivalence result is much less general but still practically relevant and more lightweight: although it requires considerations about preservation of extensional equality, it does not require stronger axioms like univalence or a larger conceptual framework.

Conclusions, outlook
In dependently typed programming in the context of Martin-Löf type theories (Martin-Löf & Sambin, 1984;Nordström et al., 1990), the problem of how to specify abstract data types for verified generic programming is still not well understood. In this work, we have shown that requiring functors to preserve extensional equality of arrows yields abstract data types that are strong enough to support the verification of non-trivial monadic laws and of generic results in domain specific languages for dynamical system and control theory.
We have shown that such a minimalist approach can be exploited to derive results that otherwise would require enforcing the relationships between monadic operatorspure, bind, join, Kleisli composition, etc. -through intensional equalities or, even worse, postulating function extensionality or similar impossible specifications.
As a consequence we have proposed to carefully distinguish between functors whose associated map can be shown to preserve extensional equality (and identity arrows and arrow composition) and functors for which this is not the case.
Current work by two of the authors shows that preservation of extensional equality is useful in designing a verified ADT for Applicative functors (McBride & Paterson, 2008) and that all Traversable functors satisfy mapPresEE.
We conjecture that carefully distinguishing between higher order functions that can be shown to preserve extensional equality and higher order functions for which this is not the case can pay high dividends (in terms of concise and correct generic implementations and avoidance of boilerplate code) also for other abstract data types.