scieee AI-readable full text Open interactive document viewer

Back to programming from Galois connections

Pereira, Paulo Ricardo Antunes

Abstract

It is clear that the trend towards higher levels of abstraction in programming methods, as well as the effort to make software design more of a scientific, engineering discipline, has led to the development of various programming paradigms and the use of rigorous proof methods to ensure the reliability and safety of critical software systems. However, the implementation of these formal methods can be challenging due to their reliance on inductive proofs following the invent-and-verify method. Despite this, some in the field continue to seek out and use these theoretical foundations in an attempt to produce high-quality software. Therefore, this study presents the potential for the correct-by-construction method, using Galois Connections and theoretical concepts from computer science to develop a methodology for constructing practically applicable software systems whose correctness is guaranteed from the outset.

Full text

University of Minho School of Engineering Paulo Ricardo Antunes Pereira Back to Programming from Galois Connections October 2023 University of Minho School of Engineering Paulo Ricardo Antunes Pereira Back to Programming from Galois Connections Master’s Dissertation Master in Informatics Engineering Work carried out under the supervision of José Nuno Oliveira (U.Minho) October 2023 Copyright and Terms of Use for Third Party Work This dissertation reports on academic work that can be used by third parties as long as the internationally accepted standards and good practices are respected concerning copyright and related rights. This work can thereafter be used under the terms established in the license below. Readers needing authorization conditions not provided for in the indicated licensing should contact the author through the RepositóriUM of the University of Minho. License granted to users of this work: CC BY https://creativecommons.org/licenses/by/4.0/ i ii Acknowledgements I am very grateful to my supervisor and mentor José Nuno Oliveira for the opportunities he has given me, all the weekly conversations in his office and the care taken to guide me very rigorously during my journey. It is an honor for me to be his student. I also want to extend my thanks to Paulo Silva, the developer of the Galculator proof assistant, for his generous allocation of time and practical assistance in refactoring Galculator, as well as for providing guidance on utilizing his proof assistant to automate the method analyzed in this thesis. Finally, I express my gratitude to my beloved ones, especially my parents and grandparents for their unconditional support and encouragement. iii iv Statement of Integrity I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. University of Minho, Braga, October 2023 Paulo Ricardo Antunes Pereira v 4.4 Non-Galois connections ................................ 64 4.4.1 repeat .................................... 64 4.4.2 words & unwords ............................... 65 4.5 Summary ....................................... 67 5 Pointfree programming from Galois connections 69 5.1 Pointfree calculation of take .............................. 69 5.2 Pointfree calculation of takeWhile ........................... 76 5.3 Pointfree calculation of uncurry zip .......................... 78 5.4 Summary ....................................... 82 6 Galculator 83 6.1 Launching Galculator ................................. 83 6.2 “Galculating” uncurry take .............................. 86 6.3 Summary ....................................... 92 7 Conclusions 93 7.1 Summary of contributions ............................... 93 7.2 Future work ...................................... 94 III Appendices 99 A Proofs 101 Proof 1 ...........................................101 Proof 2 ...........................................101 Proof 3 ...........................................102 B Laws of functional and relation calculus 103 xii Part I Introductory material 1 Chapter 1 Introduction How sound has Software Engineering proved to be as a body of knowledge since 1968, the year regarded as its birthdate? The term was coined in a conference supported by NATO that took place in October, 1968, in Garmisch, Germany, with the purpose of suggesting that software manufacture should be based on the types of theoretical foundations and practical disciplines, that are traditional in the established branches of engineering (Naur and Randell,1969). However, how well established are such theoretical foundations and practical disciplines in the Software Engineering branch? These last 50 years have shown that only a few have taken these concerns seriously (Dijkstra,1976;Jones, 1980;Gonthier,2008). As a consequence, software lacks much in quality still in our days. Development costs are high, teams are too big, with inefficient methods that lead to an uncontrolled increase of complexity, all leading to bad software products. This is not engineering at all (Bogost,2015). Still, there is hope. 1.1 Context and aims The evolution of software engineering has been characterized by a trend towards higher levels of abstraction in programming methods. In the early days of computing, programmers would manually input machine code. Eventually, tools such as assemblers, linkers, compilers, and interpreters for high-level languages were developed to make the programming process easier. This led to the emergence of various programming paradigms, including imperative and object-oriented programming, which aimed to provide programmers with ways to more clearly express the desired behavior of a software system. Simultaneously, there was a push to make software design more of a scientific, engineering discipline, leveraging the connection between mathematical proofs and computer programs — known as the Curry- Howard correspondence (Sørensen and Urzyczyn,2006) — to guide the creation of large software systems, i.e., the aforementioned theoretical foundations that any branch of engineering requires. This led to the 3 development of functional and logic programming paradigms, which advocate a more declarative style of programming, in which the programmer only specifies what a system should do rather than how it should do it (Cohen,1995). The reliability and safety of critical software systems, such as those used in life-critical applications, depend on the use of rigorous proof methods to guarantee the complete correctness of the software. Many researchers and engineers have been eager to find and use such theoretical foundations. However, these formal methods can be challenging to implement due to their reliance on inductive proofs. In fact, were it easy and all software producers would use these methods and produce great quality products. But this is not the case: formal methods end up having to be based on inductive proofs that hinder widespread acceptance. Despite this, some in the field of software engineering continue to seek out and use these theoretical foundations in an effort to produce high-quality products. While the difficulties inherent in these proof methods may hinder their widespread adoption in industry, they remain essential for ensuring the safety and reliability of critical software systems. Unfortunately, most prefer to take the easy way out. As the Verification stage in the software construction line Specification → Modeling → Implementation → Verification tends to be quite complex, most software producers eventually replace it with a Testing phase. However, tests do not prove the correctness of software. Tests only prove the existence of errors, never their absence. This is because it is impossible to test every possible input and scenario that a piece of software may encounter. As a result, it is possible for a piece of software to pass all tests but still contain defects that have not been discovered. Thus, ensuring correctness always requires use of formal methods in the Verification phase, with the inductive proof methods already mentioned. In this approach, known as invent & verify (Roggenbach et al.,2022), a system is designed and implemented based on a specification or set of requirements and then verified or validated to ensure that it meets the intended specification. But — what if one could, from the specification, immediately derive by calculation its correct implementation? Software would be ensured to be “correct inside” by mere construction, the implementation becoming a direct result of the specification. This would ensure that the software is correctly implemented according to its specification, as the process of calculation would eliminate any potential errors or deviations from the intended behavior. In other words, the software would be correct by construction because it would have been constructed according to a precise and error-free process. 4 This methodology — known as correct-by-construction (CbC) — emphasizes the importance of designing and developing systems in such a manner as to ensure their correctness from the outset (Bordis et al., 2022). It advocates the integration of verification techniques during the design and development process, rather than relying on post-deployment validation methods. This can be achieved through the use of specific formal methods that, in the end, ensure a well-established implementation fulfilling the specification. Of course, both approaches provide a high level of assurance that a system is error-free and meets its specifications since they ensure that a system is designed and implemented according to a precise, formallyspecified set of requirements, and can provide a rigorous, mathematical proof of the system’s correctness. This can be particularly important for safety-critical systems, such as those used in aviation, healthcare, or transportation, where the consequences of errors can be severe. However, the verification phase in the invent & verify approach relies, in the majority of cases, on inductive proofs, which are quite complex. Inductive proofs often involve reasoning about countably infinite sets, being challenging to understand and manipulate. Even an engineer with the expertise and a deep understanding of the underlying mathematical concepts and with a significant training and practice on proof assistants would consider these proofs quite difficult and long in real applications. Therefore, correct-by-construction approaches are highly desirable in the field of software engineering. These approaches align with the methodology employed in traditional engineering disciplines, such as civil engineering, in which the integrity of a structure is established through the utilization of sound design principles, and subsequently validated through rigorous analysis, as opposed to trial and error. The discipline of software engineering seeks to apply these principles of engineering to the development of software systems. The implementation of the correct-by-construction methodology represents a significant step towards the realization of software engineering as a bona-fide engineering discipline. What evidence have proponents of the correct-by-construction method presented in support of its effectiveness? It has been shown how certain recursive computations could be formally specified using Galois connections in an induction-free manner (Mu and Oliveira,2012). Furthermore, relation algebra (Bird and de Moor, 1997) can be used to derive functionally correct implementations from such specifications, dispensing with inductive proofs. However, this technique is not easily accessible because it requires extensive knowledge of the relation calculus (Bird and de Moor,1997) and, in particular, of a non-trivial operation called “shrinking” (Mu and Oliveira,2012). Meanwhile, the same principle was explored in a more accessible way that does not require such technical knowledge (Silva and Oliveira,2008). However, such experiments did not go beyond the exploratory phase. Therefore, the main aim of this dissertation is to start from such exploratory research and work it out 5 extensively with as many case-studies as possible to assess its practicality. Such case-study portfolio should include examples beyond classical functional programming libraries, possibly reaching dynamic programming and encompassing specification patterns that might extend the strict GC layout. The ultimate goal is to deliver a system able to support this kind of formal program derivation using the “Galculator”, a proof-assistant developed in a doctoral dissertation some time ago (Silva,2009) that is primarily based on Galois connections. This work can be framed in the broad discipline of formal methods applied to software design, stepping up the paradigm of deriving correct-by-construction programs from logic specifications. 1.2 Structure of the dissertation Chapter 2 begins by introducing the concept of a Galois connection with a well-known example, the problem of integer division, along with its application in computer science. The chapter further delves into the study of Galois connections, focusing on aspects most pertinent to this thesis. Chapter 3 provides the foundational principles of the algebra of programming, pointfree calculus with functions and relations, culminating in a critical juncture: the expression of Galois connections in a pointfree manner. This is regarded as crucial for automating the strategy proposed in the thesis. Chapter 4 introduces programming based on Galois connections, initially addressing partial orders in two significant algebras — the Peano algebra of the natural numbers and the algebra of lists. Furthermore, it expounds on the process of integrating Galois connections with predicates, as many functions in their specification involve the use of predicates and filters based on such predicates. The chapter concludes with two pivotal sections: a repertoire of functions from the Haskell Standard Prelude calculated through Galois connections and the study of functions that, despite appearing to be Galois connections, are not. In Chapter 5, three carefully selected functions from the repertoire are re-calculated, this time at the pointfree level. This style of calculation is essential to the final chapter, which addresses the use of the Galculator proof assistant. Since the Galculator exclusively operates with relational equalities (at the pointfree level), understanding how to proceed in calculating a function from its specification as a Galois connection under relational equality is crucial. Thus, Chapter 6 explains how to launch the Galculator and how to replicate Galois-connection-based proofs in this proof assistant. 6 Chapter 2 Background This chapter focuses on the state of the art related to Galois connections. Given the paramount objective of this thesis, particular attention is devoted to exploring the applications of GCs. This focus allows for the examination of the contrasting perspective inherent in GCs, specifically within the context of the easy/hard dichotomy of (Mu and Oliveira,2012;Oliveira,2023). The discussion culminates with a presentation of GCs equivalent definitions and algebraic properties. 2.1 Introducing Galois connections and its applications In general, a Galois connection (GC) is a pair of functions fand gsatisfying f z ⩽x≡z⊑g x (2.1) for all zand x, given preorders (⩽)and (⊑)(which can be the same). It expresses a “shunting” rule which enables one to exchange between function gin the upper side of a preorder (⊑)and a function fin the lower side of a preorder (⩽), in a way very similar to handling (in)equations in school algebra. Functions fand gare said to be adjoints of each other where fis the lower adjoint and gthe upper adjoint, with the (conventional) notation f⊣g. But are Galois connections a novelty for the software designer? In primary school, integer division is taught according to the following specification: x÷y is the largest natural number that, when multiplied by y , is at most x . An algorithm for calculating the division is also taught, where one finds not just the result but also the remainder, which is as follows1 x y r z x÷y=z∗y+r 1The symbol ∗is used to denote multiplication in order to distinguish it from ×, which is used to denote Cartesian products. 7 Thus, when questioned how to formally specify integer division, one may recur to that same algorithm and write z=x÷y≡ ⟨∃r: 0 ⩽r<y:x=z∗y+r⟩(2.2) which is adequate. However, the remainder ris not even mentioned in the specification. This addition only results in increased complexity. In fact, the existential quantifier makes reasoning a bit difficult. So, let us try to rewrite it using only the known facts in the specification: z∗y⩽x≡z⩽x÷y(2.3) This is precisely (2.1) instantiated with natural number inequality preorder (⩽),f= (∗y)and g= (÷y). z(∗y) |{z} f ⩽x≡z⩽x(÷y) |{z} g But is this formal specification adequate? Split the equivalence into two implications: •z⩽x÷y⇒z∗y⩽x This one tells what is needed for zto be a candidate solution of x÷y— it is required that z∗y⩽x. But there is only one solution, the largest one, which is given by the other implication: •z∗y⩽x⇒z⩽x÷y On the other hand, this one tells that, among all the candidates z(if zsatisfies z∗y⩽x, therefore being a candidate solution), z⩽x÷y. So, x÷yis the largest of the candidates. How good is this way of specifying integer division? Note that it is an equivalence universally quantified in all its variables, it is closest to the natural language specification, and it is tremendously generous with respect to inference of properties. Some of these arise from mere instantiation, as is the case of e.g. 0⩽x÷y,(z:=0) y⩽x≡1⩽x÷y,(z:=1) Other properties, for instance x÷1=x, call for properties of the lower adjoint (multiplication). Let us check its proof: z⩽x÷1 8 ≡ { GC (2.3)} z∗1⩽x ≡ { 1is the unit of multiplication } z⩽x That is, every natural number zwhich is at most x÷1is also at most xand vice versa. So x÷1and xare the same. The logic behind this style of reasoning is known as the principle of indirect equality (Dijkstra, 2001): 2 a=b≡ ⟨∀x:: x⩽a≡x⩽b⟩(2.4) Using this principle, x÷x=1(for x>0) can be derived as follows: z⩽x÷x ≡ { GC (2.3)} z∗x⩽x ≡ { 1is the unit of multiplication } z∗x⩽1∗x ≡ { operation (∗x)is injective } z⩽1 :: {indirect equality (2.4)} x÷x=1 □ More elaborate properties can be inferred from (2.3) together with indirect equality and basic properties of the “easy” adjoint (multiplication), for instance (for m,d>0): (n÷m)÷d=n÷(d∗m)(2.5) Again, blending GC (2.3) with indirect equality, one delivers and elegant and easy proof: z⩽(n÷m)÷d ≡ { GC (2.3)} z∗d⩽n÷m 2This applies to any reflexive and antisymmetric order, which encompasses of course the partial order (⩽)on the real numbers. 9 Perfect antithesis The concept of a perfect antithesis, characterized by opposition or inversion, is embodied by the notion of a bijection or isomorphism. This involves two functions fand gthat satisfy the following properties: B g '' ∼ =A f gg   f(g b) = b g(f a) = a (2.9) That is, both are lossless transformations. For example, multiplication and division are inverses of each other in the real numbers. That is, undertaking these operations does not result in any loss of information — for g:=(/y)and f:=(∗y), one gets R (/y) '' ∼ =R (∗y) gg   (b/y)∗y=b (a∗y)/y=a Imperfect antithesis In practice, data transformations often result in loss of information, e.g. png2pdf )) ≇ pdf2png ii    png2pdf ·pdf2png =id pdf2png ·png2pdf =id although our eyes may not spot the difference in most cases. These imperfect inversions result in a loss of information which does not fit in equation (2.9). However, it may be the case that one can write    f(g b)⩽b g(f a)⊑a (2.10) telling “how bad” each inversion is, by relying on two preorders (⩽)and (⊑)that capture under and over approximations : (⩽) g (((⊑) f hh(2.11) (Functions fand gare assumed monotonic above.) How Galois connections arise Let us now handle these approximations by analyzing the following diagram: g x f (g x)(⩽)//x g x a (⊑) OO f a (⩽) OO (⩽) ;; v v v v v v v v v v v v v vg(f a) (⊑)<< y y y y y y y y y y y a (⊑) OO (⊑) oo 16 where x(⩽)//yand x(⊑)//ydenote x⩽yand x⊑yrespectively. Starting with a(⊑)//g x , which means that a⊑g x, 1. since fis monotonic, one obtains f a ⩽f(g x); 2. from (2.10), one obtains f(g x)⩽x; 3. by transitivity (“arrow composition”), one obtains f a ⩽x; 4. since gis monotonic, one obtains g(f a)⩽g x; 5. again, from (2.10) and transitivity, one obtains a⊑g x. Thus, a⊑g x ⇒f a ⩽x⇒a⊑g x which leads, by circular implication, to the following equivalence f a ⩽x⇔a⊑g x (2.12) that is, Galois connection (2.1). Thus, one may also use the notation in (2.11) in order to render GCs. Back to the integer division algorithm, it is the experience of every child that x∗yis much simpler to calculate than x÷y. Nevertheless, an intriguing observation arises wherein the perceived complexity of the operation x÷ycan be effectively explained by the inherent simplicity of the operation x∗y. In fact, (∗y)⊣(÷y)conveys the underlying message: hard (÷y)is explained by easy (∗y). Exploring program specifications as GCs within the framework of this easy/hard dichotomy is at the very core of this thesis, so as to calculate “hard” adjoints from easy ones. For instance, extending this dichotomy to the aforementioned function d take, one has length z⩽n∧z≼x | {z } easy ⇔z≼d take (n,x) | {z } hard 2.3 Algebraic properties and equivalent definitions One of the main advantages of this rich theory is that once a concept is identified as an adjoint of a Galois connection, all generic properties are inherited, even when the other adjoint is not known. Let us brief these key properties which relate GCs to the underlying ordered structures. 17 • “Shunting rule” — f“shunts to the other side” and becomes g, and vice-versa: f a ⊑Bb⇔a⊑Ag b (2.13) • Upper adjoint distributes over meet (wherever this exists): g(b⊓Bb′) = g b ⊓Bg b′(2.14) • Lower adjoint distributes over join (wherever this exists): f(a⊔Aa′) = f a ⊔Af a′(2.15) • Cancellation of the lower adjoint: a⊑Ag(f a)(2.16) • Cancellation of the upper adjoint: f(g b)⊑Bb(2.17) • Lower adjoint is monotonic: a⊑Aa′⇒f a ⊑Bf a′(2.18) • Upper adjoint is monotonic: b⊑Bb′⇒g b ⊑Ag b′(2.19) • Upper adjoints preserve top elements: g⊤B=⊤A(2.20) • Lower adjoints preserve bottom-elements: f⊥A=⊥B(2.21) 18 • for partial orders, the so-called semi-inverse properties: f=f·g·f(2.22) g=g·f·g(2.23) Besides, a most useful ingredient of Galois connections lies in the fact that they build up on top of themselves thanks to a number of combinators which enable one to construct (on the fly) new connections out of existing ones (Oliveira,2020b). A fundamental result that Galois-connected functions can be combined to form new GCs is given via functional composition. Given two GCs as follows (⩽) g (((⊑) f hh k (((≼) h hh a new GC arises: (⩽) k·g (((≼) f·h hh The equivalence is quite straightforward, cf. (f·h)x⩽z ⇔ { composition; f⊣g} h x ⊑g z ⇔ { h⊣k; composition } x≼(k·g)z □ A second major result is that every relator6that distributes through binary intersections preserves GCs (Backhouse and Backhouse,2004). This means that, for every such relator Rand given a GC (⩽) g (((⊑) f hh a new GC arises: R(⩽) Rg **R(⊑) Rf jj 6See Section 3.2 which expounds the notion of a relator within the relation algebra framework. 19 Finally, Backhouse (2004) presents some alternative definitions in order to easily identify (f,g)as a GC between posets (partially ordered sets)7(A,⊑A)and (B,⊑B). Among them, the following two are noteworthy: Alternative definition 1 •fand gare both monotonic; • for all x∈Band y∈A,x⊑Bg(f x)and f(g y)⊑Ay Alternative definition 2 •gis monotonic; • for all x∈B,x⊑Bg(f x); • for all x∈Band y∈A,x⊑Bg y ⇒f x ⊑Ay 2.4 Summary The calculational power of Galois connections has been shown to be effective in function specification and in deriving them by calculation using the indirect equality method, dispensing with explicit inductive proofs. This same method allows for the derivation of properties of the adjoint functions prior to their implementation — an excellent and highly desired application of GCs. Having demonstrated its practicality and usefulness, important algebraic properties as well as equivalent definitions of GCs have also been revealed, which will certainly facilitate the specification of further functions in terms of GCs. 7A poset is a pair (P,(⩽)), where Pis a set and (⩽)is partial order on P. 20 Chapter 3 Going pointfree Oliveira (2020b) conducts a comprehensive examination of GCs within the framework of relation algebra. In this chapter, the mathematical concept of GC is presented from this perspective. Furthermore, this chapter will provide us with the necessary means to formally specify programs through GCs and carry out precise calculations to derive their implementations. To fulfill that purpose, the chapter begins with a brief overview of the pointfree relational calculus and concludes with the formulation of GCs in the form of relational equalities. The use of pointfree notation is essential to provide a rigorous justification for the developed theory and for proof-support purposes. In fact, by exploring the domain of calculating with functions and relations, we shall unlock the potential for precise program specification and its correct-by- construction implementation. It should be noted that some laws are not introduced in this chapter for the purpose of streamlining the content. However, all the laws and properties used are presented in Appendix B. 3.1 Calculating with functions The concept of a function is well-known to anyone with basic school education. The understanding of functions permeates mathematics, as it is grounded in the established framework of sets and set-theoretical functions. Functional programming, which is basically programming with functions, extends beyond the act of writing code for computers. It embodies the notion that different branches of programming have the potential to adopt a functional structure or expression, while also encompassing the concept of transforming abstract and inefficient programs into efficient ones through calculation. Functions and types In Functional Programming (FP), functions are the most important objects. They act like a “black box” that produces a specific result from a given input. Functions will be denoted by lowercase letters. We write f:A→Bto indicate that freceives values of type Aand produces values of 21 type B. This is usually referred as the function signature or type. How is the output of a function produced? The answer is given when inspecting the inside of the black box — that is where the calculation rule of the function is to be found. This calculation rule, also called the function’s behavior, is specified directly at an arbitrary point in the domain (also called variable). For example, in the definition f x =x+1, it is directly specified on an arbitrary xin the domain of fthat the behavior of fon that xis to add 1to it. It is precisely this way of defining functions that is studied in high school. By contrast, pointfree definitions are characterized by the absence of variables, being built instead through the combination of simpler functions using a limited set of combinators. The choice of these combinators is dictated by the power of the laws associated with them. Some of these combinators are analyzed below. Identity and constant functions Identity functions are those that merely copy the input to the output: f a =a, for f:A→Aand a∈A. In this case, fis said to be the identity function on A. As expected, every type Xhas its own identity function idX. However, subscripts will be omitted whenever they are implicit in the context. Thus, a “single” identity function can be assumed. Unlike the identity function, which does not lose any information, constant functions lose all (or nearly all) information. Regardless of the input data, the output is always the same value. The notation to be used will be underlining. Therefore, let Cbe a non-empty datatype and c∈C. The everywhere c function, for an arbitrary type A, is defined as cA=cwhose signature is A→C. Similar to what occurs with identity functions, subscripts will be omitted whenever they are implicit in the context. Functional composition A cornerstone of FP is the functional composition combinator, which “chains” two functions in the following way: Af// g·f 99 Bg//C In mathematics, one usually says that the outputs of function fmust be contained within the domain of function g. However, in computer science the rule is simpler, yet more restrictive: the output type of f must match the input type of g. Nonetheless, the notation employed is the same: g·f, which can be read as “gcomposed with f” or “gafter f”, and is precisely defined as (g·f)x=g(f x). Products As expected, not all functions can be combined via functional composition. For example, functions f:A→Band g:A→Care a case where functional composition cannot be applied. However, since both functions share the same input type, they can be combined via the binary operator ⟨,⟩called 22 split . For functions fand g, one has ⟨f,g⟩:A→B×C. This operator satisfies h=⟨f,g⟩ ⇔    π 1·h=f π 2·h=g (3.1) for all h:A→B×Cand given projections π 1:A×B→Aand π 2:A×B→B. Set B×Cis given by the Cartesian product of Bwith C, i.e., B×C={(b,c)|b∈B∧c∈C} and the split combinator is defined by ⟨f,g⟩a= (f a,g a)(3.2) The “tensor product” operator ×can also be defined on functions via the split combinator: f×g=⟨f· π 1,g· π 2⟩(3.3) IT preserves composition and identity: (f×g)·(h×k)=(f·h)×(g·k)(3.4) idA×idB=idA×B(3.5) Coproducts As previously explained, the functional combinator split was created with the aim of combining functions that do not meet the requirements of functional composition but share the same domain. The “dual” situation corresponds to functions sharing the codomain instead. Thus, functions f:A→Cand g:B→Ccan be combined via the binary operator [,]called either or join . One has [f,g]:A+B→C, where A+Bis the disjoint union , A+Bdef ={i1a|a∈A} ∪ {i2b|b∈B} assuming the “tagging” functions i1and i2, whose signatures are Ai1//A+B B i2 oo. These functions associate different tags in order to ensure that values of type Aand values of type Bdo not mix in the set A+B. They are called injections of the disjoint union — i1is said to “inject” values to the left, while i2“injects” values to the right. In words, “either we are on the left side and execute for we are in the right side and execute g.” Therefore, the either combinator is defined by [f,g]xdef =   x=i1a⇒f a x=i2b⇒g b (3.6) 23 and satisfies k= [f,g]⇔   k·i1=f k·i2=g (3.7) for all k:A+B→C. Similarly to ×, the operator +can also be defined on functions, now via the either combinator: f+g= [i1·f,i2·g](3.8) Again, it preserves composition and identity: (f+g)·(h+k)=(f·h)+(g·k)(3.9) idA+idB=idA+B(3.10) McCarthy’s conditional Most functional programming languages provide pointwise conditional expressions in the form if p x then f x else g x (3.11) which translates into the following process: given a predicate p:A→Band two functions f,g:A→B, if p x holds then the process results in f x, otherwise in g x, i.e.,    p x ⇒f x ¬(p x)⇒g x In order to rewrite the expression (3.11) in a pointfree style, let us start by assuming that p x has already been calculated. In this case, either fis executed or gis executed. This latter operation is clearly the combinator [f,g]. So, the goal is, if p x holds, the argument is injected on the left side, so that the operation f x is executed; otherwise, the argument is injected on the right side and g x is executed instead of f x. This injection choice is performed by the operation p?, called the guard associated with the predicate p, defined by p?x=if p x then i1xelse i2x Thus, the expression (3.11), rewritten in a pointfree style, is given by [f,g]·p?. Note that p?is much more informative than the predicate itself, as it already gives us the result of testing pon a given input. All this leads to the well-known functional combinator “McCarthy’s conditional” that is usually denoted by the expression p→f,g. Therefore, p→f,gdef = [f,g]·p?(3.12) 24 The use of the either combinator suggests that, when reasoning about conditionals, one can turn to the algebra of coproducts as a potential aid. This results in the following properties: h·(p→f,g) = p→h·f,h·g(3.13) (p→f,g)·h= (p·h)→f·h,g·h(3.14) p?·f= ( f+f)·(p·f)?(3.15) namely, the fusion laws and the natural property of the guard, respectively. Exponentials Given a function f:C×A→B, one intends to construct a family of functions of the type A→Baccording to the following approach: for each c∈C, the function fc:A→B fcadef =f(c,a) (3.16) is constructed. In other words, the construction of this family is a function of the type C→(A→B), meaning that given a c∈C, it produces a function of the type A→B. Functions of this kind are called higher-order functions — functions that not only produce functions but also receive functions as arguments. To represent the type A→B(or B←A), we shall use the notation BA. Thus, BAdef ={g|g:A→B}(3.17) corresponds to the type inhabited by functions from Ato B. This means that the functional declaration g:A→Bis equivalent to g∈BA. Since the purpose of functions is to be applied to arguments, the introduction of the apply combinator is quite intuitive: ap :BA×A→B ap (f,a)def =f a (3.18) Now, going back to the function f:C×A→B, let’s recall the strategy of producing a function fc∈BA for each c∈C. As mentioned before, this process corresponds to a function of the type C→BA, which expresses fas a family of functions of the type A→Bindexed by the type C. Such functions will be referred to as transposes, and the notation fwill be used to represent them, read as “curry of f”. As expected, fand fare mutually related by the following property: f(c,a)=(f c)a(3.19) 25 with Mary |{z} a is loved by | {z } R◦ John |{z} b That is, loves◦=(is loved by). Naturally, the converse of a converse is the relation itself — converse is an involution (R◦)◦=R(3.44) and commutes with composition in a contravariant way: R·S◦=S◦·R◦(3.45) Converses of functions enjoy a number of properties from which the following is singled out as a way to introduce/remove them from logical expressions (useful when dealing with more complex types): b(f◦·R·g)a⇔(f a)R(g b)(3.46) Relation inclusion and equality While function equality can be expressed by extensionality, f=g≡ ⟨∀ a:a∈A:f a =g a⟩ there are two methods, besides direct equality, to prove relational equality: circular inclusion , and indirect equality . Both of these rely on the notion of relation inclusion, defined as follows: R⊆S≡ ⟨∀ a,b:: aRb⇒a S b⟩(3.47) Circular inclusion arrives at equality by proving, in both directions, that one relation is smaller than, or, at most, equal to the other. This method is often called “ping-pong”, and in proofs of this type the two steps will be referred to as the “ping” step and the “pong” step. R=S≡R⊆S∧S⊆R(3.48) In indirect equality, we prove that inclusion under one relation is equivalent to inclusion under the other. That is to say, one shows that all relations having Ras a subset have Sas a subset, and vice-versa. R=S≡ ⟨∀ X:: X⊆R⇔X⊆S⟩(3.49) ≡ ⟨∀ X:: R⊆X⇔S⊆X⟩(3.50) 32 Meet and join Like sets, two relations of the same type, say B A R,S oo, can be intersected or joined in the obvious way: b(R∩S)a≡aRa ∧b S a (3.51) b(R∪S)a≡aRa ∨b S a (3.52) R∩Sis usually called meet (intersection) and R∪Sis called join (union). They lift pointwise conjunction and disjunction, respectively, to the pointfree level. Their meaning is nicely captured by the following universal properties: X⊆R∩S≡X⊆R∧X⊆S(3.53) R∪S⊆X≡R⊆X∧S⊆X(3.54) Taxonomy of binary relations Let us now define some basic properties of some relations, which will be the starting point to describe more complex properties. • A relation is reflexive if and only if every element is related to itself: Ris reflexive ⇔id ⊆R(3.55) • A relation is correflexive if and only if it is a subset of the identity relation: Ris correflexive ⇔R⊆id (3.56) • A relation is transitive if and only if cRawhenever cRband bRa: Ris transitive ⇔R·R⊆R(3.57) • A relation is antisymmetric iff b=awherever bRaand aRb: Ris antisymmetric ≡R∩R◦⊆id (3.58) A preorder is a relation that is both reflexive and transitive. An antisymmetric preorder is referred to as a partial order . Well-known examples of such partial orders are the numerical comparison operator (⩽) and relation inclusion. In subsequent chapters, the properties of this and other operators as partial orders will play a crucial role in many proofs. Additionally, a relation is: 33 • entire if it is defined for every element of its domain. • injective if no two elements of its domain are related to the same element. • surjective if, for every element of its range, there is at least one element related to it. • simple if each element of its domain is related to at most one element. To define these last four properties using relation algebra, we first introduce the notions of kernel and image : ker R=R◦·R(3.59) img R=R·R◦(3.60) Thee kernel of Rrelates inputs that share shared outputs, and its image relates outputs to shared inputs. Rinjective: ker R⊆id (3.61) Rsimple: img R⊆id (3.62) Rentire: id ⊆ker ·R(3.63) Rsurjective: id ⊆img ·R(3.64) This can be “translated” to the following table: Reflexive Coreflexive ker Rentire Rinjective R img Rsurjective Rsimple R Figure 1shows a taxonomy of binary relations based on the combination of the previous four properties. It is quite interesting because it denotes the central role played by functions. binary relation [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ V V V V V V h h h h h h ccccccccccccccccccccc injective Q Q Qentire m m m mV V V V V V Vsimple P P P hhhhhhhsurjective n n n representation Q Q Qfunction V V V V V V h h h h h habstraction n n n n injection U U U Usurjection hhhh bijection (isomorphism) Fig. 1: Binary relation taxonomy 34 The properties of different kinds of relations have dualities under converse, that is: Ris a bijection ⇔Rand R◦are both functions (3.65) Ris injective ⇔R◦is simple (3.66) Ris surjective ⇔R◦is entire (3.67) By extension, the converse of a representation is an abstraction, the converse of an injection is a surjection, and vice-versa. Due to transitivity of inclusion and the fact that a larger relation also has a larger (or at most equal) kernel and image, making a relation bigger or smaller can preserve some of its properties, as follows: Sis injective (simple) ⇐S⊆Rand Ris injective (simple) (3.68) Sis entire (surjective) ⇐R⊆Sand Ris entire (surjective) (3.69) Relators As a generalization of a functor, a parametric datatype Gis said to be a relator wherever, given a relation B A R oo,GRextends Rto G-structures forming the new relation GBGA GR oodepicted by the following diagram: A R  GA GR  BGB (3.70) By definition, relators, in addition to obeying the two properties of functors — commutation with identity GidA=id (GA)(3.71) and with composition G(R·S)=(GR)·(GS)(3.72) — they also obey a third property — commutation with converse G(R◦)=(GR)◦(3.73) Top and bottom The ⊤(“top”) and ⊥(“bottom”) relations b⊤a≡True (3.74) b⊥a≡False (3.75) 35 are the upper and lower bound for all relations of a certain relational type, meaning that, for any relation B A R oo: ⊥ ⊆ R⊆ ⊤ (3.76) These relations are the zero and identity elements of the relational join and meet operations: R∪ ⊥ =R(3.77) R∩ ⊥ =⊥(3.78) R∪ ⊤ =⊤(3.79) R∩ ⊤ =R(3.80) Sometimes it is possible to discard relations composed with ⊤to use the laws introduced above. This can be done if the relation in question is entire: ⊤·R=⊤ ⇐ R is entire (3.81) Since ⊤is larger than any relation (3.76), it suffices to prove ⊤ ⊆ ⊤·R: ⊤ ⊆ ⊤·R ⇐ { Ris assumed entire; raising the lower side } ⊤·R◦·R⊆ ⊤·R ⇐ { monotonicity } ⊤·R◦⊆ ⊤ ≡ { ⊤above everything } True □ Predicates as relations Given a predicate p:A→B, the relation ϕ p:A→Adefined by ϕ p=id ∩true◦·p(3.82) for true x =True, is said to be the coreflexive relation that represents predicate pas binary relation, cf. y ϕ px⇔y=x∧p y (3.83) Two crucial derived properties are: R· ϕ p=R∩ ⊤· ϕ p(3.84) 36 ϕ q·R=R∩ ϕ q·⊤ (3.85) which respectively mean b(R· ϕ p)a⇔bRa ∧(p a)(3.86) b( ϕ q·R)a⇔bRa ∧(q b)(3.87) Finally, a notable property is that the composition of coreflexives coincides with their meet: ϕ q· ϕ p= ϕ q∩ ϕ p(3.88) Relational catamorphisms They are identical to functional catamorphisms, with the distinction that now the F-algebra β in diagram (3.29) is a relation, say R, and Fis a relator instead of a functor. Thus, there is a unique relation of type B←T, denoted by LRM, such that LRM·inT=R·FLRMholds, cf. T LRM  outT '' ∼ =F T FLRM  inT ff BFB R ff (3.89) A crucial property is the fusion law : S·LRM=LQM⇐S·R=Q·FS(3.90) along with its weaker versions: Q·LSM⊆LRM⇐Q·S⊆R·FQ(3.91) LRM⊆Q·LSM⇐R·FQ⊆Q·S(3.92) Relational catamorphism are central to relation algebra (Bird and de Moor,1997). Oliveira (2023) shows how they arise from (3.41) for the adjunction that yields the powerset monad. 3.3 Galois connections go pointfree In Section 2.1, a Galois connection was defined pointwise as a pair of functions fand gsatisfying f z ⩽x⇔z⊑g x 37 for all zand x, given preorders (⩽)and (⊑). Now, relation composition, relational equality and converses can be used to derive the GC pointfree definition, as follows. f z ⩽x⇔z⊑g x ≡ { (3.46); identity } z(f◦·(⩽)) x⇔z((⊑)·g)x ≡ { (3.47) twice; circular inclusion (3.48)} f◦·(⩽)=(⊑)·g The rendering of Galois connections as relational equalities, f◦·(⩽)=(⊑)·g(3.93) will prove very useful in the sequel. 3.4 Summary A brief introduction to pointfree calculus and relation algebra was presented, highlighting relevant concepts such as functions, functional combinators, binary relations, relation composition, converses, relation inclusion and equality, and the taxonomy of binary relations. This study is crucial in formulating Galois connections as relational equalities, as the use of pointfree notation is essential for rigorously justifying the entire developed theory. 38 Part II Contribution 39 Chapter 4 Programming from Galois connections A pivotal factor in Galois connection-based programming lies in the specification of the underlying orders. This chapter will show how the (pointfree) relational definition of these (inductive) orders is essential for accurately inferring the functions specified by the connections they rely upon. 4.1 Inductive partial orderings 4.1.1 Peano algebra Giuseppe Peano (1858-1932) was a famous Italian mathematician who made significant contributions to the field of mathematics, particularly in the area of mathematical logic and the foundations of arithmetic. Peano is well-known for developing the so-called Peano axioms , which provide a set of five axioms for the construction of the natural numbers. The study of these axioms is not relevant to this discussion. The relevance lies in what these axioms translate into, that is, a unique way of constructing natural numbers: Every natural number in N0 is either 0 or the successor of another natural number. Thus, for succ :N0→N0 succ n def =n+1 (4.1) and inN0= [0,succ](4.2)    outN00=i1() outN0(n+1) = i2n (4.3) 41 ≡ { one-point }    s⊑[ ] ⇔s= [ ] s⊑(h:t)⇔ ⟨∃y:s= (h:y):y⊑t⟩ ∨ s⊑t (4.22) The proofs of reflexivity and transitivity are identical to those of the prefix order, cf. id ⊆(⊑) ≡ { idT=LinTM;inT= [nil,cons]} L[nil,cons]M⊆L[nil,cons ∪ π 2]M ⇐ { monotonicity } [nil,cons]⊆[nil,cons ∪ π 2] ≡ { coproducts }    nil ⊆nil cons ⊆cons ∪ π 2 ≡ { trivial; R⊆R∪S} True □ and (⊑)·(⊑)⊆(⊑) ≡ { definitions } (⊑)·L[nil,cons ∪ π 2]M⊆L[nil,cons ∪ π 2]M ⇐ { catamorphism fusion } (⊑)·[nil,cons ∪ π 2]⊆[nil,cons ∪ π 2]·(id +id ×(⊑)) ≡ { fusion and absorption }    (⊑)·nil ⊆nil (⊑)·(cons ∪ π 2)⊆(cons ∪ π 2)·(id ×(⊑)) ≡ { (⊑)·nil =nil (4.21); linearity } (⊑)·cons ∪(⊑)· π 2⊆cons ·(id ×(⊑)) ∪ π 2·(id ×(⊑)) ≡ { ∪-universal property }    (⊑)·cons ⊆cons ·(id ×(⊑)) ∪ π 2·(id ×(⊑)) (⊑)· π 2⊆cons ·(id ×(⊑)) ∪ π 2·(id ×(⊑)) 48 ≡ { π 2-natural property }    (⊑)·cons ⊆cons ·(id ×(⊑)) ∪(⊑)· π 2 (⊑)· π 2⊆cons ·(id ×(⊑)) ∪(⊑)· π 2 ≡ { (⊑)·cons =cons ·(id ×(⊑)) ∪(⊑)· π 2(4.21); trivial } True □ However, the method for proving antisymmetry does not follow the same scheme, since the definition of the converse of (⊑)is not a relational catamorphism:    y⊒[ ] ⇔True y⊒(h:t)⇔ ⟨∃(a,b):y= (a:b):(a=h∧b⊒t)∨b⊒(h:t)⟩ ≡ { going pointfree }    (⊒)·nil =⊤ (⊒)·cons =cons ·((id ×(⊒)) ∪ π ◦ 2·(⊒)·cons) ≡ { right linearity }    (⊒)·nil =⊤ (⊒)·cons =cons ·(id ×(⊒)) ∪cons · π ◦ 2·(⊒)·cons Because this calls for a concept that extends that of a catamorphism, known as hylomorphism (Bird and de Moor,1997), this proof is left for future work, see Section 7.2. Suffix partial order Another order that will be required in the sequel is the suffix order, namely when calculating functions such as drop and dropWhile. Taking as starting point    s⋞[ ] ⇔s= [ ] s⋞(h:t)⇔s= (h:t)∨s⋞t (4.23) one easily seems that it is another example of a non-catamorphic definition:    s⋞[ ] ⇔s= [ ] s⋞(h:t)⇔s= (h:t)∨s⋞t ≡ { go pointfree }    (⋞)·nil =nil (⋞)·cons =cons ∪(⋞)· π 2 (4.24) 49 ≡ { coproducts } (⋞)·inList = [nil,cons ∪(⋞)· π 2](4.25) For the same reasons as above, the proofs for reflexivity, transitivity, and antisymmetry require hylomorphisms and are deferred for future work. 4.2 Predicates in Galois connections Some GCs that will be subject of study in Section 4.3 deal with predicates in a very particular pattern — when expressed via pointwise f z ⩽x≡z⊑g x zneeds to satisfy some given predicate p. Thus, one could simply write p z ∧f z ⩽x≡p z ∧z⊑g x However, this approach is not particularly suitable for indirect equality proofs, nor does it resemble the typical format of a GC. Nevertheless, this is an easily surmountable issue — observe that in these cases, the upper adjoint yields values that satisfy p. Thus, it suffices to restrict the respective order to values that satisfy p, and the lower adjoint merely receives z’s that satisfy the given predicate, that is, (f·castp)z⩽x≡z⊑pg x (4.26) where castptype-casts Ap(type Arestricted to the elements that satisfy predicate p) to its general type A. Note that, since the orders are parametric, the subscript can be omitted. For instance, consider the function takeWhile specified as takeWhile p l yields the longest prefix of a sequence whose elements satisfy predicate p . Recurring to (4.26), it can be formally specified as castall p z≼l≡z≼takeWhile p l (4.27) Someone might complain it can be quite tiresome to handle two “different” types. But what does this function cast practically mean? Clearly, castpzRy ≡p z ∧zRy (4.28) Thus, (4.27) could be rewritten as all p z ∧z≼l≡z≼takeWhile p l (4.29) 50 which reads very effectively “the largest prefix whose elements satisfy predicate p”. Generally, equivalence (4.26) is rewritten as, dropping the subscript, p z ∧f z ⩽x≡z⊑g x (4.30) Finally, concerning to relation equalities, what can be said about this type-casting? First, GC (4.26) is directly given in pointfree as cast◦ p·f◦·(⩽)=(⊑p)◦·g(4.31) However, when calculating it from (4.30), one obtains p z ∧f z ⩽x⇔z⊑g x ≡ { one-point and trading } ⟨∃a:z=a∧p a :f a ⩽x⟩ ⇔ z⊑g x ≡ { coreflexives } ⟨∃a:z ϕ pa:f a ⩽x⟩ ⇔ z⊑g x ≡ { going pointfree } ϕ p·f◦·(⩽)=(⊑)·g(4.32) So, cast◦ poperates just like ϕ p— it enforces the coreflexive in the “lower” type. This result will prove very useful when dealing with pointfree specifications in Chapter 5. For instance, takeWhile p can be specified via GC as a relational equality by cast◦ all p ·(≼)=(≼)·takeWhile p (4.33) which can be rewritten as ϕ all p ·(≼)=(≼)·takeWhile p (4.34) 4.3 Repertoire of functions calculated from GCs In order to evaluate the scope of the proposed correct-by-construction method, a series of functions taken from the Haskell standard libraries have been subject to the check whether they are specifiable (and implementable) by GCs or not. Positive examples are given first, along with their pointwise derivations. Counter-examples will be given later. 51 •x÷y is the largest natural number that, when multiplied by y , is at most x . z×y⩽x≡z⩽x÷y(4.35) As already calculated in Section 2.1: -- Calculated implementation of div div :: (Ord t, Num a, Num t) => t-> t-> a div x y = if x < y then 0else 1 + div (x - y) y • Given a partial order (⩽) , min m n yields the greatest value which is simultaneously ‘less or equal’ than m and n according to the given order. z⩽m∧z⩽n≡z⩽min m n (4.36) –if m⩽n z⩽min m n ≡ { GC (4.36)} z⩽m∧z⩽n ≡ { since m⩽n,z⩽mentails z⩽n} z⩽m :: {indirect equality over (⩽)partial order } min m n =m –if ¬(m⩽n) z⩽min m n ≡ { GC (4.36)} z⩽m∧z⩽n ≡ { since ¬(m⩽n) = n<m,z⩽nentails z<mwhich entails z⩽m} z⩽n :: {indirect equality over (⩽)partial order } min m n =n -- Calculated implementation of min min :: Ord a=> a-> a-> a min m n = if m <= n then melse n 52 • Given a partial order (⩾) , max m n yields the greatest value which is simultaneously ‘greater or equal’ than m and n according to the given order. z⩾m∧z⩾n≡z⩾max m n (4.37) Its calculation is analogous to min (4.36). -- Calculated implementation of max max :: Ord a=> a-> a-> a max m n = if m >= n then melse n • Given a partial ordering (⩽) , minimum l yields the greatest value which is ‘less or equal’ than all elements of l according to the given order. all (z⩽)l≡z⩽minimum l (4.38) –minimum [h] z⩽minimum [h] ≡ { GC (4.38)} all (z⩽) [h] ≡ { definition of all } z⩽h :: {indirect equality over (⩽)partial order } minimum [h] = h –minimum (h:t) z⩽minimum (h:t) ≡ { GC (4.38)} all (z⩽) (h:t) ≡ { definitions of all } z⩽h∧all (z⩽)t ≡ { GC (4.38)} z⩽h∧z⩽minimum t ≡ { GC (4.36)} 53 z⩽min h (minimum t) :: {indirect equality over (⩽)partial order } minimum (h:t) = min h (minimum t) -- Calculated implementation of minimum minimum :: Ord a=> [a] -> a minimum [h] =h minimum (h:t) =min h (minimum t) • Given a partial ordering (⩾) , maximum l yields the smallest value which is ‘greater or equal’ than all elements of l according to the given order. all (⩾z)l≡z⩾maximum l (4.39) Calculation is analogous to that of minimum (4.38). -- Calculated implementation of maximum maximum :: Ord a=> [a] -> a maximum [h] =h maximum (h:t) =max h (maximum t) •take n x yields the longest prefix of a sequence up to some given length n . length z⩽n∧z≼x≡z≼take n x (4.40) Already calculated in Section 2.1, but this time given on its original (curried) form. -- Calculated implementation of take take :: Int -> [a] -> [a] take 0 _ = [] take _ [] = [] take (n+1) (h:xs) =h:take n xs •takeWhile p l yields the longest prefix of a sequence whose elements satisfy predicate p . castall p z≼l≡z≼takeWhile p l (4.41) –takeWhile p [ ] z≼takeWhile p [ ] ≡ { GC (4.41)} castall p z≼[ ] 54 ≡ { type-casting (4.28)} z≼[ ] :: {indirect equality over list prefixing (≼)} takeWhile p [ ] = [ ] –takeWhile p (h:t) z≼takeWhile p (h:t) ≡ { GC (4.41)} castall p z≼l ≡ { type-casting (4.28)} all p z ∧z≼l ≡ { (≼)definition (4.18)} all p z ∧(⟨∃b:z= (h:b):b≼t⟩ ∨ z= [ ]) ≡ { distribution } (all p z ∧z= [ ]) ∨ ⟨∃b:z= (h:b):all p z ∧(b≼t)⟩ ≡ { all p z ⇐z= [ ] } z= [ ] ∨ ⟨∃ b:z= (h:b):all p z ∧(b≼t)⟩ ≡ { all p (x:xs)≡p x ∧all p xs } z= [ ] ∨ ⟨∃ b:z= (h:b):p h ∧all p b ∧b≼t⟩ ≡ { type-casting (4.28)} z= [ ] ∨ ⟨∃ b:z= (h:b):p h ∧castall p b≼t⟩ ≡ { GC (4.41)} z= [ ] ∨ ⟨∃ b:z= (h:b):p h ∧b≼takeWhile p t⟩ *if p h z= [ ] ∨ ⟨∃ b:z= (h:b):b≼takeWhile p t⟩ ≡ { (≼)definition (4.18)} z≼h:takeWhile p t :: {indirect equality over list prefixing (≼)} takeWhile p (h:t) = h:takeWhile p t 55 *if ¬(p h) z= [ ] ≡ { (≼)definition (4.18)} z≼[ ] :: {indirect equality over list prefixing (≼)} takeWhile p (h:t) = [ ] -- Calculated implementation of takeWhile takeWhile :: (a -> Bool)-> [a] -> [a] takeWhile p [] = [] takeWhile p (h:t) = if p h then h:takeWhile p t else [] •drop n x yields the longest suffix of a sequence whose length does not exceed length x−n . length z⩽length x−n∧z⋞x≡z⋞drop n x (4.42) –drop 0x z⋞drop 0x ≡ { GC (4.42)} length z⩽length x∧z⋞x ≡ { z⋞xentails length z⩽length } z⋞x :: {indirect equality over list suffixing (⋞)} drop 0x=x –drop n [ ] z⋞drop n [ ] ≡ { GC (4.42)} length z⩽n∧z⋞[ ] ≡ { z⋞[ ] ⇔z= [ ] which entails length z⩽n} z⋞[ ] :: {indirect equality over list suffixing (⋞)} drop n [ ] = [ ] 56 –drop (n+1) (h:t) z⋞drop (n+1) (h:t) ≡ { GC (4.42)} length z⩽length (h:t)−(n+1)∧z⋞(h:t) ≡ { length definition; arithmetics; suffix definition (4.23)} length z⩽length t−n∧(z= (h:t)∨z⋞t) ≡ { distribution } (length z⩽length t−n∧z= (h:t)) ∨(length z⩽length t−n∧z⋞t) ≡ { GC (4.42)} (length t+1⩽length t−n)∨(z⋞drop n t) ≡ { 1⩽−nis false } z⋞drop n t :: {indirect equality over list suffixing (⋞)} drop (n+1) (h:t) = drop n t -- Calculated implementation of drop drop :: Int -> [a] -> [a] drop 0 x =x drop n [] = [] drop (n+1) (h:t) =drop n t Assert drop (length l)l= [ ] z⋞drop (length l)l ≡ { GC (4.42)} length z⩽length l−length l∧z⋞[ ] ≡ { trivial } length z⩽0∧z⋞[ ] ≡ { length z⩽0⇔z= [ ] ⇔z⋞[ ] } z⋞[ ] :: {indirect equality over list suffixing (⋞)} drop (length l)l= [ ] 57 length z⩽n∧all (≡x)z ≡ { repeat property (4.48)} length z⩽n∧z≼repeat x ≡ { GC (4.40)} z≼take n (repeat x) :: {indirect equality over list prefixing (≼)} replicate n x =take n (repeat x) -- Calculated implementation of replicate replicate :: a-> Int -> [a] replicate n x =take n (repeat x) 4.4 Non-Galois connections The study carried out in this dissertation of identifying functions that can be specified as Galois connections was primarily targetted at predefined functions from Haskell Standard Prelude. In some cases, in spite of exhibiting similarities with the ones addressed in the previous section, upon closer examination they could not be specified as GCs. As exmples of such counter-examples, the functions repeat and words & unwords are scrutinized below. 4.4.1 repeat Function repeat of the Haskell Standard Prelude operates by generating an infinite sequence through the perpetual replication of a specified element. For instance, the outcome of repeat 7 will be an unending sequence [7,7,7,...]. The idea that immediately comes to mind is to postulate the following property that relates function ‘repeat‘ with the prefix partial order: all (≡x)z⇔z≼repeat x (4.48) The question is: is this property a Galois connection? Clearly, this is not the case — there is no order on the lower side of the connection. Even by employing the cast function as studied in Section 4.2, it is not possible to express the property in the form: f z ⩽x⇔z≼repeat x form some order (⩽)and some lower adjoint f. 64 Nevertheless, nothing prevents one from using such a property (cf. the replicate calculation in the repertoire Section 4.3) and from employing indirect equality over the prefix partial order to derive the definition of repeat, cf. z≼repeat x ≡ { property (4.48)} all (≡x)z ≡ { definition of all } ⟨∃t:z=x:t:all (≡x)t⟩ ∨ z= [ ] ≡ { property (4.48)} ⟨∃t:z=x:t:t≼repeat x⟩ ∨ z= [ ] ≡ { prefix definition (4.18)} z≼x:repeat x :: {indirect equality over list prefixing (≼)} repeat x =x:repeat x -- Calculated implementation of repeat repeat :: a-> [a] repeat x =x:repeat x This example demonstrates that indirect equality serves as an effective proof technique and is not limited to Galois connections exclusively. 4.4.2 words & unwords In the Haskell Standard Prelude, some pairs of functions can be found that, at first glance , appear to constitute Galois connections. One example is the pair words &unwords that plays a fundamental role in text processing: •words:String→[String]is employed to split a string by spaces or whitespace characters (spaces, tabs, and newline characters) — it essentially parses a textual input into a list of individual words. • “conversely”, unwords :[String]→String takes a list of words and concatenates them into a single string, using the space character as a delimiter. 65 Note that the expression ‘conversely’ referring to unwords is enclosed in commas. In fact, the pair does not form an isomorphism, cf. > words . unwords $ ["ola "] ["ola"] But — is it a GC? If so, by (2.22), unwords·words·unwords =unwords should hold. However, it clearly does not, since > unwords $ ["Hello "] "Hello " > unwords . words . unwords $ ["Hello "] "Hello" shows such a property failing at least once. This suffices to state that words and unwords do not form a Galois connection. Another pair of similar functions in the Haskell Standard Prelude, is lines & unlines . The distinction lies in the fact that they operate with newline characters rather than spaces: •lines :String→[String]divides a string into a list of substrings, each representing a line of text. The division is determined by the presence of a newline character. • “conversely”, unlines:[String]→String accepts a list of strings (each representing a line of text) and concatenates them into a single string. Basically, it inserts newline characters between the substrings. Again, the expression ‘conversely’ is enclosed in commas, since it does not form an isomorphism, cf. > lines . unlines $ ["Hello.\n"] ["Hello.",""] But, this time, no cases were found where the laws of semi-inverses (2.22) and (2.23) failed. However, this does not guarantee that it is a Galois connection, even though, through other properties, it may indeed seem to be (recall Section 2.3). Hence, it appears quite probable to define the following Galois connection: unlines z ⩽l≡z⊑lines l (4.49) with the orders yet to be defined. Note, however, that both lines &unlines and words &unwords could well be a particular case of a pair of functions defined by 66 sep :: Eq a=> a-> [a] -> [[a]] sep a =splitOn [a] unsep :: a-> [[a]] -> [a] unsep a =concat . (intersperse [a]) It can be argued that words is more powerful since it separates not just by a single character, but the truth is that unwords uses only one such character. Nevertheless, one could define words,unwords,lines, and unlines in the following way, lines =sep '\n' unlines =unsep '\n' words =sep ' ' unwords =unsep ' ' leading to a likely Galois connection, unsep a z ⩽l≡z⊑sep a l (4.50) the analysis of which is left for future work. 4.5 Summary Programming from Galois connections was examined as a method for calculating programs from their specifications under Galois connections. To do so, the most common partial orders pertaining to both the Peano and the finite list algebras were initially defined. Particular attention was given to rigorously proving that they indeed constitute partial orders. Following this, a significant result regarding predicates in Galois connections was presented. This result is subsequently demonstrated in the repertoire, where several functions from the Haskell Standard Prelude were specified under Galois connections, and their respective implementations were computed. Finally, some attention was paid to functions that initially appeared to belong to Galois connections but were subsequently shown not to do so. Alternative approaches were outlined in such cases. 67 68 Chapter 5 Pointfree programming from Galois connections As previously mentioned in the introduction, one of the objectives of this work is to automate the proofs using the Galculator proof assistant, a process which will be examined in the following chapter. However, it is worth noting that the Galculator operates exclusively at the pointfree level, with relational equalities. To assess such pointfree proof style, three functions were selected from the repertoire of the previous chapter for pointfree recalculation, now with their GC specifications turned into relational equalities. Pointfree reasoning is usually advocated to ensure a fully correct and error-free alternative to pointwise proofs, which “conceal” many intermediate steps. Indeed, the rigor of pointfree proofs will become evident when comparing the respective proofs for each selected function. The chosen functions are take,takeWhile, and zip. We shall analyze each of them in sequence. These functions were selected since, collectively, they suffice to characterize the aforementioned calculation method. With the calculation of these three functions as a foundation, the remainder are calculated in a similar manner. Note that, since relational equalities are being employed, the uncurried versions of the take and zip will be used. Towards the end, the power of adjoint recursion (3.41) will allow us to derive the original curried functions. In the case of takeWhile, the predicate will be fixed, i.e., we shall work with takeWhile p for a given suitable predicate p. 5.1 Pointfree calculation of take Function d take has been specified via pointwise GC (2.8) and a pointwise derivation was made. Now, rendered as a relational equality (3.93), let us work with the pointfree specification of d take: ⟨length,id⟩◦·((⩽)×(≼)) = (≼)·d take (5.1) First of all, since its specification recurs to the converse of length, one may calculate length◦to derive some important equalities to be used in the proofs. 69 Therefore, and since length =L[0,succ · π 2]M, length◦=L[0,succ · π 2]M◦ ={catamorphisms definition } ([0,succ · π 2]·(id +id ×length)·outList)◦ ={converses } inList ·(id +id ×length◦)·[0,succ · π 2]◦ ={+-definition } inList ·[i1,i2·(id ×length◦)]·[0,succ · π 2]◦ ={either and converse } inList ·(i1·0◦∪i2·(id ×length◦)· π ◦ 2·succ◦) ={either and converse; inN0definition } inList ·[i1,i2·(id ×length◦)· π ◦ 2]·outN0 ={+-definition; converses } inList ·(id +(id ×length)◦· π ◦ 2)·outN0 ={converses } inList ·(id + π ◦ 2·length◦)·outN0 ={+-composition } inList ·(id + π ◦ 2)·(id +length◦)·outN0 ={catamorphisms definition } LinList ·(id + π ◦ 2)M which means that    length◦·0=nil length◦·succ =cons ·(length · π 2)◦(5.2) and from which one may derive length◦·(⩽)∩nil =nil (5.3) nil ⊆length◦·(⩽)(5.4) (length ·cons)◦·(⩽)·succ = (length · π 2)◦·(⩽)(cf. Proof 1) (5.5) Note that while length is a List-catamorphism, length◦is an N0-catamorphism. 70 Finally, let us work with the three aforementioned cases of d take: •z≼d take (0,x)which becomes the pointfree expression (≼)·d take ·(0×id) (≼)·d take ·(0×id) ={GC (5.1)} ⟨length,id⟩◦·((⩽)×(≼))·(0×id) ={×-definition and composition; constants natural property; pairing and converse } length◦·(⩽)·0∩(≼)· π 2 ={(⩽)definition (4.9); length◦·0=nil (5.2)} nil ∩(≼)· π 2 ={nil ⊆(≼)· π 2since img π 2=id and nil =L[nil,nil]M⊆(≼)by monotonicity } (≼)·nil :: {indirect equality over prefix partial order (≼)} d take ·(0×id) = nil (5.6) •z≼d take (n,[ ]) which becomes (≼)·d take ·(id ×nil) (≼)·d take ·(id ×nil) ={GC (5.1)} ⟨length,id⟩◦·((⩽)×(≼))·(id ×nil) ={×-definition and composition; constants natural property; pairing and converse } length◦·(⩽)· π 1∩(≼)·nil ={(≼)·nil =nil ⊆length◦·(⩽)· π 1(cf. Proof 3)} (≼)·nil :: {indirect equality over prefix partial order (≼)} d take ·(id ×nil) = nil (5.7) •z≼d take (n+1,h:t)which becomes (≼)·d take ·(succ ×cons) (≼)·d take ·(succ ×cons) ={GC (5.1)} 71 ⟨length,id⟩◦·((⩽)×(≼))·(succ ×cons) ={×-composition and definition } ⟨length,id⟩◦·⟨(⩽)·succ · π 1,(≼)·cons · π 2⟩ ={pairing and converse } length◦·(⩽)·succ · π 1∩(≼)·cons · π 2 ={(≼)definition (4.17)} length◦·(⩽)·succ · π 1∩(nil ∪cons ·(id ×(≼))· π 2) ={distributivity; k·R=kwhen Ris entire; id ×(≼)is entire since (≼)is reflexive } (length◦·(⩽)·succ · π 1∩nil)∪(length◦·(⩽)·succ · π 1∩cons ·(id ×(≼))· π 2) ={nil ⊆length◦·(⩽)·succ · π 1(check (5.4)) } nil ∪(length◦·(⩽)·succ · π 1∩cons ·(id ×(≼))· π 2) ={distributivity, since cons◦·cons is injective; contravariance } nil ∪cons ·((length ·cons)◦·(⩽)·succ · π 1∩(id ×(≼))· π 2) ={(5.5)} nil ∪cons ·((length · π 2)◦·(⩽)· π 1∩(id ×(≼))· π 2) ={contravariance; ×-definition and fusion; pairing definition } nil ∪cons ·(length◦· π ◦ 2·(⩽)· π 1∩( π ◦ 1· π 1· π 2∩ π ◦ 2·(≼)· π 2· π 2)) ={associativity } nil ∪cons ·( π ◦ 1· π 1· π 2∩( π ◦ 2·length◦·(⩽)· π 1∩ π ◦ 2·(≼)· π 2· π 2)) ={distributivity since π ◦ 2is injective; pairing definition } nil ∪cons ·⟨ π 1· π 2,length◦·(⩽)· π 1∩(≼)· π 2· π 2⟩ ={pairing and converse; identity } nil ∪cons ·⟨ π 1· π 2,⟨length,id⟩◦·⟨(⩽)· π 1,(≼)· π 2· π 2⟩⟩ ={×-definition } nil ∪cons ·⟨ π 1· π 2,⟨length,id⟩◦·((⩽)×(≼)· π 2)⟩ ={×-absorption and composition } nil ∪cons ·(id ×⟨length,id⟩◦·((⩽)×(≼)) ·⟨ π 1· π 2,id × π 2⟩) ={GC (5.1)} 72 nil ∪cons ·((id ×(≼)·d take)·⟨ π 1· π 2,id × π 2⟩) ={×-composition } nil ∪cons ·(id ×(≼))·(id ×d take)·⟨ π 1· π 2,id × π 2⟩) ={constants natural property } nil ·(id ×d take)·⟨ π 1· π 2,id × π 2⟩ ∪ cons ·(id ×(≼))·(id ×d take)·⟨ π 1· π 2,id × π 2⟩) ={left linearity } (nil ∪cons ·(id ×(≼)))·(id ×d take)·⟨ π 1· π 2,id × π 2⟩ ={(≼)definition (4.17)} (≼)·cons ·(id ×d take)·⟨ π 1· π 2,id × π 2⟩ :: {indirect equality over prefix partial order (≼)} d take ·(succ ×cons) = cons ·(id ×d take)·⟨ π 1· π 2,id × π 2⟩(5.8) This leads to the already presented definition of d take: d take (0,) = [ ] d take (,[ ]) = [ ] d take (n+1,h:t) = h:d take (n,t) which is clearly the following G-hylomorphism on lists: N0×A∗ d take  1+A×(N0×A∗) Gd take  (1+N0)×A∗ ψ oo L inN0 rr A∗1+A×A∗ inList oo where ψ = [i1· π 1,( π 2+xr)·distr ·(id ×outList)]·distl xr =⟨ π 1· π 2,id × π 2⟩ Lf=f×id Gf=id +id ×f That is, d take =inList ·Gd take · ψ ·L outN0 73 ={union distributes through intersection } (map π ◦ 1·cons ·(id ×(≼))· π 1∩map π ◦ 2·cons ·(id ×(≼))· π 2)∪nil ={map R·cons =cons ·(R×map R);cons is injective } cons ·(( π ◦ 1×map π ◦ 1·(≼))· π 1∩( π ◦ 2×map π ◦ 2·(≼))· π 2)∪nil ={×-functor composition } cons ·(( π ◦ 1×map π ◦ 1)·(id ×(≼))· π 1∩( π ◦ 2×map π ◦ 2)·(id ×(≼))· π 2)∪nil ={pairing and converse; ×-functor definition } cons ·⟨ π 1×map π 1, π 2×map π 2⟩◦·((id ×(≼))×(id ×(≼))) ∪nil ={⟨ π 1×map π 1, π 2×map π 2⟩◦= (id ×⟨map π 1,map π 2⟩)◦·transpose (Proof 2)} cons ·(id ×⟨map π 1,map π 2⟩)◦·transpose ·((id ×(≼)) ×(id ×(≼))) ∪nil ={converses; transpose natural property } cons ·(id ×⟨map π 1,map π 2⟩◦)·(id ×((≼)×(≼)))·transpose ∪nil ={×-functor composition } cons ·(id ×⟨map π 1,map π 2⟩◦·((≼)×(≼)))·transpose ∪nil ={GC (5.12)} cons ·(id ×(≼)·c zip)·transpose ∪nil ={×-functor-composition } cons ·(id ×(≼))·(id ×c zip)·transpose ∪nil ={left linearity; constants’ natural property } (cons ·(id ×(≼)) ∪nil)·(id ×c zip)·transpose ={(≼)definition } (≼)·cons ·(id ×c zip)·transpose :: {indirect equality over prefix partial order (≼)} c zip ·(cons ×cons) = cons ·(id ×c zip)·transpose This leads to the already presented definition of c zip: c zip ([ ],) = [ ] c zip (,[ ]) = [ ] c zip (h1:t1,h2:t2)=(h1,h2):c zip (n,t) 80 which is clearly the following G-hylomorphism on lists: A∗×A∗ c zip  1+(A×A)×(A∗×A∗) Gc zip  (1+A×A∗)×A∗ ψ oo L inList rr (A×A)∗1+(A×A)×(A×A)∗ inList oo where ψ (i1(),) = i1() ψ (,[ ]) = i1() ψ (i2(h1,t1),h2:t2) = i2((h1,h2),(t1,t2)) Lf=f×id Gf=id +id ×f That is, c zip =inList ·Gc zip · ψ ·L outList Now, let us again recur to the power of adjoint recursion in order to define the original (curried) version of zip as an adjoint catamorphism: A∗ take  1+A×A∗ inList oo id+id×take  ((A×A)∗)A∗1+A×((A×A)∗)A∗ inList·G ε · ψ oo zip =LinList ·G ε · ψ Mwhere ε =ap The process to simplify the gene of catamorphism zip is similar to the catamorphism take. Thus, zip is defined by the following pointwise definition: zip :: [a]→[b]→[(a,b)] zip =L[f,g]Mwhere f= [ ] g[ ] = [ ] g(h1,k) (h2:t2)=(h1,h2):k t2 81 5.4 Summary Pointfree level reasoning ensures complete correctness in program calculation, in contrast with pointwise calculations that often “conceal” many intermediate steps. Moreover, automation is enabled by tools that, such as the Galculator, adopt such a reasoning paradigm. In this chapter three functions — namely, take,takeWhile and zip — were chosen to be recalculated, this time at the pointfree level. In the case of the take and zip, whose uncurried versions had been calculated, the study of adjunctions and catamorphisms ultimately facilitated the calculation of the original curried version. Galois-connection pointfree proofs rely, as previously mentioned, on relational equalities, which is the framework employed by the aforementioned Galculator proof assistant. This is the subject of the chapter that follows. 82 Chapter 6 Galculator The proposal of a design strategy for software development starting from specifications cast in the form of Galois connections, leading to correct-by-construction (CbC) artifacts, has taken most of the current dissertation. Looking at some of the calculations that have been performed by hand, it becomes clear that CbC comes with a cost: it may take a significant number of steps to reach the final implementation. This calls for some kind of proof-assistance. The prototype proof assistant known as Galculator (Silva and Oliveira,2008) is distinctively centered on the algebra of Galois connections. Its effectiveness is heightened when integrated with techniques like the pointfree transform (recall Section 3.3) and proof methods such as the indirect equality principle. Clearly, the Galculator is a first choice for assisting in calculating functions specified by Galois connections, provided these are appropriately expressed at the pointfree level, as shown in the previous chapter. This chapter will demonstrate how the tool can be used as proof assistant in such proofs. The potential for proof automation supported by the Galculator tool will be showcased taking the calculation of the function take as demonstration example. 6.1 Launching Galculator After refactoring part of the code of the Galculator due to updates in the Haskell programming language and its libraries since the tool was developed years ago, all modules run properly. The Galculator was containerized from the Haskell image, and the base command is ghci with the necessary flags for compiling all modules. With the container up and running, it is sufficient to execute the main function, cf. 83 ghci> main ___ __ _ ___ _ _ _ __ _____ __ ___ / _ \ / \ | | / __|| | | || | / \ |_ _|/ \| \ / /_\/ / /\ \ | | | | | | | || | / /\ \ | | | | || / / /_\\ / ___ \| |___| |__ | |_| || |___ / ___ \ | | | | || |\ \ \____//_/ \_/ \____|\___|\____/ \____|/_/ \_/ |_| \___/|_| \_\ Paulo Silva ([email protected]) Universidade do Minho, Braga, Portugal Galculator> and the Galculator is on. Within the scope of this study, it is imperative to understand the process of creating modules encompassing the laws, properties, and definitions pertinent to the programs whose calculations are sought. Equally important is to,learn how to conduct indirect equality proofs. Modules and terminology Concerning modules, these must be stored in files with the .gal extension and must begin by specifying the module’s name, e.g. module integer. The terminology used in the modules is quite user-friendly. Some examples that elucidate what one can expect to find in a Galculator module follow: •EQUIV meet_assoc (MEET (MEET (Var r) (Var s)) (Var t)) (MEET (Var r) (MEET (Var s) (Var t))); This equivalence reflects the associative property of the meet operation. As observed, MEET is part of a set of reserved words and in this case refers to the operator ∩. Note that the expressions are polymorphic, as they can take any expression — cf. the use of Var. •EQUIV involution (CONV (CONV (Var r))) (Var r); EQUIV contravariance (CONV (COMP (Var r) (Var s))) (COMP (CONV (Var s)) (CONV (Var r))); The two equivalences presented just above — namely, contravariance and converse involution — emphasize the use of the reserved word CONV denoting the converse of a relation. •DEF const (Fun (TVar a) (Prod (TVar a) (TVar b))); DEF zero INT; 84 DEF succ (Fun Int Int); DEF leq (Ord Int); DEF prefix (Ord (List (TVar t3))); DEF leq_prefix (Ord (Prod Int (List (TVar t4)))); It is noteworthy to highlight function declaration via signatures declared from right to left. Please note that the constant function is defined in an uncurried way, as it takes a pair. (Recall the need for making functions uncurried due to the use of pointfree notation.) An integer zero and the function succ are defined, as well as the orders less than or equal in the natural numbers, prefix in lists, and the order as the product of these last two. •EQUIV leq_zero (COMP (ORD (REF leq)) (FUN (LEFTSEC (REF const) (REF zero)))) (FUN (LEFTSEC (REF const) (REF zero))); EQUIV prefix_nil (COMP (ORD (REF prefix)) (FUN (LEFTSEC (REF const) (REF empty_list)))),→ (FUN (LEFTSEC (REF const) (REF empty_list))); The code above is the Galculator equivalent to: (⩽)·0=0 (≼)·nil =nil One thus needs to define the functions 0and nil, obtained through the use of LEFTSEC. This operator takes a function that accepts a pair of arguments and will fix the first argument — it corresponds to fixing arguments in Haskell’s transposition. The examples given above are sufficient to get a glimpse of how the Galculator is implemented. For a more comprehensive understanding, it is recommended to delve into some of the modules provided in the Galculator’s Github repository. Galois connections and proofs by indirect equality To establish a Galois connection in the Galculator, one only needs to input the lower adjoint, followed by the upper adjoint, the lower-side order and then the upper-side order right after GDef <name_of_gc>. For instance, the Galois connection that specifies take (5.1) is given by GDef take_gc (APPLY (REF to_func) (SPLIT (FUN (REF length)) ID)) (REF take) (REF leq_prefix) (REF prefix); 85 NB:to_func is used to retrieve the function embedded in a relation since SPLIT is, as defined in Galculator, a relation. Indirect equality proofs are conducted within the command line using the prove command followed by the equality to be demonstrated. For instance, after composing within a module, say take.gal including all that is needed for proving the first base case of function take (5.6), the following commands are executed, Galculator> load take Galculator> prove EQUIV take_zero_id (COMP (FUN (REF take)) (PROD (FUN (LEFTSEC (REF const) (REF zero))) ID)) (FUN (LEFTSEC (REF const) (REF empty_list))) ,→ ,→ Galculator> left Galculator> indirect low (REF prefix) indicating the intent to start the proof named take_zero_id from the left-hand side of the equality through indirect equality over the prefix order. This proof alongside with the second base case of take will be undertaken in the next section. 6.2 “Galculating” uncurry take Let us recall the two base cases of function d take, that is, d take ·(0×id) = nil d take ·(id ×nil) = nil Also recall their calculations (5.6) and (5.7), respectively. Note that Galculator carries out the proof step by step, and some trivial steps, like associativity, are hidden, but the Galculator needs to perform them explicitly. The first case starts with the pointfree equality d take·(0×id) = nil, cf. (5.6), and then it is stated that the proof starts from the left side of the equality. Subsequently, the proof by indirect equality over the prefix partial order is introduced, having the following first steps:1 Galculator> prove EQUIV take_zero_id (COMP (FUN (REF take)) (PROD (FUN (LEFTSEC (REF const) (REF zero))) ID)) (FUN (LEFTSEC (REF const) (REF empty_list))) ,→ ,→ Galculator> show Current proof: 1Some text of the Galculator logs is omitted to streamline the reading. 86 --------------------------------------------------------------- (take . ((<zero>const) >< id)) <=> (<empty_list>const) --------------------------------------------------------------- Galculator> left Galculator> indirect low (REF prefix) Galculator> show Current proof: --------------------------------------------------------------- (take . ((<zero>const) >< id)) <=> (<empty_list>const) --------------------------------------------------------------- (prefix . (take . ((<zero>const) >< id))) Galculator> Now, proceeding with the proof, one must use the associativity of composition. Since it is defined by EQUIV comp_assoc (COMP (COMP (Var r) (Var s)) (Var t)) (COMP (Var r) (COMP (Var s) (Var t))); that is, it is inverted, one need to recur to the command inv, cf. Galculator> inv apply comp_assoc Galculator> show ((prefix . take) . ((<zero>const) >< id)) The proof proceeds by calling the shunting rule (automatically derived from the GC): Galculator> once inv shunt take_gc Galculator> show (((to_func <length, id>)* . leq_prefix) . ((<zero>const) >< id)) Now, one must apply the associativity of composition again: Galculator> apply comp_assoc Galculator> show Current proof: ((to_func <length, id>)* . (leq_prefix . ((<zero>const) >< id))) Now, notice that the product of ⩽with ≼was defined as a specific order, meaning that the order is the product itself. Therefore, it is necessary to return the product of the two orders in a way to proceed with the definition of the product. This step is accomplished by the following equivalence EQUIV leq_prefix_def (REF leq_prefix) (APPLY (REF to_ord) (PROD (ORD (REF leq)) (ORD (REF prefix))));,→ 87 which uses the function to_ord that handles the retrieval of the order embedded in a relation, cf. -- Retrieving the order embedded in a relation DEF to_ord (Fun (Ord (TVar t22)) (Rel (TVar t22) (TVar t22))); EQUIV to_ord_cancel (ORD (APPLY (REF to_ord) (Var o))) (Var o); In this way, the following commands are executed: Galculator> once apply leq_prefix_def Galculator> once apply to_ord_cancel Galculator> show Current proof: ((to_func <length, id>)* . ((leq >< prefix) . ((<zero>const) >< id))) The proof proceeds with the respective laws — ×-fusion, id-natural property, ×-definition, associativity of composition, “free-theorem” of a constant function, cf. Galculator> once apply prod_fusion Galculator> once apply natural_id_right Galculator> once apply prod_def Galculator> once apply comp_assoc Galculator> once apply const_nat Galculator> show Current proof: ((to_func <length, id>)* . <(leq . (<zero>const)), (prefix . pi2)>) Notice that <length, id> is a parameter of to_func. Recall this is needed because the SPLIT combinator within the Galculator definitions is defined as a relation. Thus, one has to retrieve the function embedded in that relation. The same happens with the identity function, since ID is defined as a relation. For that, one uses the following: -- Retrieving the function embedded in a relation DEF to_func (Fun (Fun (TVar t20) (TVar t21)) (Rel (TVar t20) (TVar t21))); EQUIV to_func_cancel (FUN (APPLY (REF to_func) (Var f))) (Var f); EQUIV to_func_id (APPLY (REF to_func) ID) FId; Therefore, the proof continues as follows with Galculator> once apply to_func_cancel Galculator> show Current proof: (<length, id>* . <(leq . (<zero>const)), (prefix . pi2)>) 88 and the laws of pairing and converse, id◦=id,id-natural property and (⩽)·0=0, cf. Galculator> once apply pairing_converse Galculator> once apply conv_id Galculator> once apply natural_id_left Galculator> once apply leq_zero Galculator> show Current proof: ((length* . (<zero>const)) /\ (prefix . pi2)) Now, recall that properties length◦·0=nil and nil ∩(≼· π 2) = nil were used in the proof. Thus, one has to add these to the module, -- conv length . zero = nil EQUIV conv_length_zero (COMP (CONV (FUN (REF length))) (FUN (LEFTSEC (REF const) (REF zero)))) (FUN (LEFTSEC (REF const) (REF empty_list))); -- nil `cap` (pref . p2) = nil EQUIV assert1 (MEET (FUN (LEFTSEC (REF const) (REF empty_list))) (COMP (ORD (REF prefix)) (FUN (REF pi2)))),→ (FUN (LEFTSEC (REF const) (REF empty_list))); Using these equivalences one gets Galculator> once apply conv_length_zero Galculator> once apply assert1 Galculator> show Current proof: (<empty_list>const) which is equivalent to (≼)·nil by (4.17), thus Galculator> inv apply prefix_nil Galculator> show Current proof: (prefix . (<empty_list>const)) Thus, the proof by indirect equality is now complete: 89 bag :: Eq a=> [a] -> a-> Int bag [] _ = 0 bag (h:t) x =bagtx+(if x == h then 1else 0) However, (7.3) is an over simplification inadequate for what the function actually does: nub cannot yield just the longest sublist, because there may exist more than one and, in that case, it must return the one that preserves the order of the initial occurrences. As an example, consider nub [1,2,1,3,2,1,0] = [1,2,3,0]. Sublist [1,3,2,0]is also one of the longest sublists whose elements do not repeat but the order of the initial occurrences must be preserved — 2appears before 3. The aim is to reformulate the sublist partial order in a manner that ensures this nuance, thus correctly calculating the function nub. In the field of the inductive partial orders that were shown to underpin the derivation of GC-adjoints as recursive functions, some orderings were found to be harder to handle than others. For instance, the antisymmetry of the sublist ordering still needs to be proved, as the converse of this order is not a catamorphism. Therefore, an alternative approach to the proof needs to be explored. Another example is the suffix ordering which, not being a relational catamorphism, needs a different strategy to prove its partial order basic properties. Finally, as previously mentioned about the Galculator proof assistant, the presented proofs were limited to function take, and the use of coreflexives and predicates was not tested. It would be interesting to observe how Galculator performs with proofs like takeWhile, whose pointfree calculation is provided in Section 5.2. Additionally, implementing the auto command, which attempts to automatically complete the proof, would be beneficial. This is because it was observed that the proofs follow a very similar structure. Furthermore, it would be even more intriguing if, with this automation, Galculator could autonomously draw conclusions about real-life, sizeable specifications. This would (will?) be indeed software correct-by-construction. 96 Bibliography K. Backhouse and R. Backhouse. Safety of abstract interpretations for free, via logical relations and galois connections. Science of Computer Programming , 51(1):153–196, 2004. ISSN 0167-6423. doi: https://doi.org/10.1016/j.scico.2003.06.002. URL https://www.sciencedirect.com/ science/article/pii/S0167642304000164. Mathematics of Program Construction (MPC 2002). R. Backhouse. Mathematics of Program Construction . Univ. of Nottingham, 2004. Draft of book in preparation. 608 pages. R. Bird and O. de Moor. Algebra of Programming . Series in Computer Science. Prentice-Hall, 1997. I. Bogost. Programmers: Stop calling yourselves engineers. The Atlantic , November 2015. URL https://www.theatlantic.com/technology/archive/2015/11/ programmers-should-not-call-themselves-engineers/414271/. T. Bordis, L. Cleophas, A. Kittelmann, T. Runge, I. Schaefer, and B. W. Watson. Re-corc-ing key: Correctby-construction software development based on key. In Wolfgang Ahrendt, Bernhard Beckert, Richard Bubel, and Einar Broch Johnsen, editors, The Logic of Software. A Tasting Menu of Formal Methods , Lecture Notes in Computer Science (including subseries Lecture Notes in Artificial Intelligence and Lecture Notes in Bioinformatics), pages 80–104, Germany, 2022. Springer. ISBN 978-3-031-08165-1. doi: 10.1007/978-3-031-08166-8_5. Publisher Copyright: © 2022, Springer Nature Switzerland AG. B. Cohen. A brief history of formal methods. Formal Aspects of Computing , 01 1995. E.W. Dijkstra. A Discipline of Programming . Prentice-Hall, 1976. E.W. Dijkstra. Indirect equality enriched (and a proof by netty). https://www.cs.utexas.edu/ users/EWD/ewd13xx/EWD1315.PDF, 2001. G. Gonthier. Formal proof — the fourcolor theorem. Notices of the AMS , 2008. URL https://www. ams.org/notices/200811/tx081101382p.pdf. 97 C.B. Jones. Software Development — A Rigorous Approach . Series in Computer Science. Prentice-Hall International, Upper Saddle River, NJ, USA, 1980. ISBN 0138218846. C.A.R. Hoare (series editor). S.-C. Mu and J.N. Oliveira. Programming from Galois connections. JLAP , 81(6):680–704, 2012. P. Naur and B. Randell, editors. Software Engineering: Report on a conference sponsored by the NATO SCIENCE COMMITTEE, Garmisch, Germany, 7th to 11th October 1968 . Scientific Affairs Division, NATO, 1969. J.N. Oliveira. A note on the under-appreciated for-loop. Technical Report TR-HASLab:01:2020 (pdf), HASLab/U.Minho and INESC TEC, 2020a. J.N. Oliveira. Biproducts of galois connections, January 2020b. Presentation at the IFIP WG 2.1 #79 Meeting, Otterlo, NL. (Slides available from the author’s website: https://ifipwg21wiki.cs.kuleuven.be/IFIP21/Otterlo). J.N. Oliveira. Program Design by Calculation, 2022. Draft of textbook in preparation, current version: September 2022. Informatics Department, University of Minho (PDF). J.N. Oliveira. Why adjunctions matter — a functional programmer perspective. In Proceedings WADT’22 , LNCS. Springer-Verlag, 2023. In the press. M. Roggenbach, A. Cerone, B.-H. Schlingloff, G. Schneider, and S. A. Shaikh. Formal Methods for Software Engineering - Languages, Methods, Application Domains . Texts in Theoretical Computer Science. An EATCS Series. Springer, 2022. ISBN 978-3-030-38799-0. doi: 10.1007/978-3-030-38800-3. URL https://doi.org/10.1007/978-3-030-38800-3. P.F. Silva. On the Design of a Galculator . PhD thesis, University of Minho, May 2009. P.F. Silva and J.N. Oliveira. ’Galculator’: functional prototype of a Galois-connection based proof assistant. In PPDP ’08: 10th int. ACM SIGPLAN conf. on Principles and practice of declarative programming , pages 44–55. ACM, 2008. M. H. Sørensen and P. Urzyczyn. Lectures on the Curry-Howard isomorphism . Elsevier, Amsterdam; Oxford, 2006. ISBN 0444520775 9780444520777. URL https: //www.worldcat.org/title/lectures-on-the-curry-howard-isomorphism/ oclc/1171193011&referer=brief_results. 98 Part III Appendices 99 Appendix A Proofs Proof 1 (length ·cons)◦·(⩽)·succ ={length definition } (succ ·length · π 2)◦·(⩽)·succ ={(⩽)definition ; distribution (twice) ; contravariance } π ◦ 2·length◦·succ◦·0·(⩽)∪ π ◦ 2·length◦·succ◦·succ ·(⩽) ={succ is injective } π ◦ 2·length◦·succ◦·0·(⩽)∪ π ◦ 2·length◦·(⩽) ={succ◦·0=⊥} π ◦ 2·length◦·(⩽) □ Proof 2 ⟨ π 1×map π 1, π 2×map π 2⟩◦ ={pairing definition } ( π ◦ 1·( π 1×map π 1)∩ π ◦ 2·( π 2×map π 2))◦ ={converses } ( π ◦ 1×map π ◦ 1)· π 1∩( π ◦ 2×map π ◦ 2)· π 2 ={×-definition } ⟨ π ◦ 1· π 1,map π ◦ 1· π 2⟩· π 1∩ ⟨ π ◦ 2· π 1,map π ◦ 2· π 2⟩· π 2 ={pairing definition } 101 ( π ◦ 1· π ◦ 1· π 1∩ π ◦ 2·map π ◦ 1· π 2)· π 1∩( π ◦ 1· π ◦ 2· π 1∩ π ◦ 2·map π ◦ 2· π 2)· π 2 ={distributivity twice } ( π ◦ 1· π ◦ 1· π 1· π 1∩ π ◦ 2·map π ◦ 1· π 2· π 1)∩( π ◦ 1· π ◦ 2· π 1· π 2∩ π ◦ 1·map π ◦ 2· π 2· π 2) ={∩-associativity } ( π ◦ 1· π ◦ 1· π 1· π 1∩ π ◦ 1· π ◦ 2· π 1· π 2)∩( π ◦ 2·map π ◦ 1· π 2· π 1∩ π ◦ 2·map π ◦ 2· π 2· π 2) ={distributivity twice } π ◦ 1·( π ◦ 1· π 1· π 1∩ π ◦ 2· π 1· π 2)∩ π ◦ 2·(map π ◦ 1· π 2· π 1∩map π ◦ 2· π 2· π 2) ={pairing definition; pairing and converse } π ◦ 1·⟨ π 1· π 1, π 1· π 2⟩ ∩ π ◦ 2·⟨map π 1,map π 2⟩◦·⟨ π 2· π 1, π 2· π 2⟩ ={×-definition twice; pairing and converse } ⟨ π 1,⟨map π 1,map π 2⟩· π 2⟩◦·⟨ π 1× π 1, π 2× π 2⟩ ={×-functor and transpose definition } (id ×⟨map π 1,map π 2⟩)◦·transpose □ Proof 3 nil ⊆length◦·(⩽)· π 1 ≡ { constants’ natural property } nil · π 1⊆length◦·(⩽)· π 1 ≡ { shunting; img π 1is surjective } nil ⊆length◦·(⩽) ≡ { (5.4)} True □ 102 Appendix B Laws of functional and relation calculus Lowercase letters denote functions, and uppercase letters denote relations. Uppercase letters in sans serif font indicate functors and relators. Composition Pointwise definition b(R.S)c≡ ⟨∃a:bRa :a S c⟩ Identity R·id =id ·R=R Associativity of composition R·(S·T)=(R·S)·T Converses Universal X◦⊆Y≡X⊆Y◦ Involution (R◦)◦=R Contravariance (R·S)◦=S◦·R◦ Isomorphism R⊆S=S◦⊆R◦ “A pocket rule” b(f◦·R·g)a≡(f b)R(g a) Relation inclusion Pointwise R⊆S⇔ ⟨∃ a,b:: bRa⇒b S a⟩ Reflection R⊆R Transitivity R⊆S∧S⊆T⇒R⊆T Top and bottom ⊥ ⊆ R⊆ ⊤ Absorption R·⊥ =⊥·R=⊥ Relation equality Pointwise R=S⇔ ⟨∀ a,b:(a∈A∧b∈B):bRa ⇔b S a⟩ Indirect equality (1) R=R≡ ⟨∀X:: X⊆R⇔X⊆S⟩ Indirect equality (2) R=R≡ ⟨∀X:: R⊆X⇔S⊆X⟩ 103 Functions Shunting (1) f·R⊆S≡R⊆f◦·S Shunting (2) R·f◦⊆S≡R⊆S·f Constants Natural property (functions) k·f=k Natural property (relations) k·R⊆k Truth functions true =True ∧false =False Fusion f·k=f k Relation union Universal property R∪S⊆X≡R⊆X∧S⊆X Right linearity R·(S∪T)=(R·S)∪(R·T) Left linearity (S∪T)·R= (S.R)∪(T.R) Converse (R∪S)◦=R◦∪S◦ Bottom R∪ ⊥ =R Top R∪ ⊤ =⊤ Relation intersection Universal property X⊆R∩S≡X⊆R∧X⊆S Right distribution (S∩Q)·R= (S.R)∩(Q.R)⇐ Q·img R⊆Q ∨ S·img R⊆S Left distribution R·(Q∩S)=(R.Q)∩(R.S)⇐ ker R·Q⊆Q ∨ ker R·S⊆S Converse (R∩S)◦=R◦∩S◦ Bottom R∩ ⊥ =⊥ Top R∩ ⊤ =R 104 Pairing and products Pairing universal property X⊆ ⟨R,S⟩ ⇔ π 1·X⊆R∧ π 2·X⊆S Pairing Fusion ⟨R,S⟩· T=⟨R·T,S·T⟩ ⇐ R·img T⊆R ∨ S·img T⊆S Fusion (functions) ⟨R,S⟩· f=⟨R.f,S.f⟩ Pairing definition ⟨R,S⟩= π ◦ 1·R∩ π ◦ 2·S Pairing and converse ⟨R,S⟩◦·⟨X,Y⟩=R◦·X∩S◦·Y Functor-×composition (R×S)·(P×Q)=(R·P)×(S·Q) Functor-×definition R×S=⟨R· π 1,S· π 2⟩ Functor-×converse (R×S)◦=R◦×S◦ Coproducts Universal property X= [R,S]⇔X·i1=R∧X·i2=S Fusion R·[S,T]=[R·S,R·T] Definition [R,S] = R·i1◦∪S·i2◦ Absorption [R,S]·(P+Q)=[R·P,S·Q] Either and converse [R,S]·[T,U]◦=R·T◦∪S·U◦ i1-natural property (i+j)·i1=i1·i i2-natural property (i+j)·i2=i2·j Functor-+composition (R+S)·(P+Q)=(R·P)+(S·Q) Functor-+definition R+S= [i1·R,i2·S] Functor-+converse (R+S)◦=R◦+S◦ Catamorphisms Universal property X=LRM≡X·inT=R·(FX) Monotonicity LRM⊆LSM⇐R⊆S Fusion S·LRM=LQM⇐S·R=Q·FS Fusion weaker version 1 Q·LSM⊆LRM⇐Q·S⊆R·FQ Fusion weaker version 2 LRM⊆Q·LSM⇐R·FQ⊆Q·S Reflection LinTM=idT 105