Department of Computing Science Catamorphism-Based Program

Total Page:16

File Type:pdf, Size:1020Kb

Department of Computing Science Catamorphism-Based Program Department of Computing Science Catamorphism-Based Program Transformations for Non-Strict Functional Languages L´aszl´oN´emeth A thesis submitted in partial fulfilment of the requirements for the degree of Doctor of Philosophy in Computing Science at the University of Glasgow November 2000 c L´aszl´oN´emeth 2000 Abstract In functional languages intermediate data structures are often used as glue to connect separate parts of a program together. These intermediate data structures are useful because they allow modularity, but they are also a cause of inefficiency: each element need to be allocated, to be examined, and to be deallocated. Warm fusion is a program transformation technique which aims to eliminate intermediate data structures. Functions in a program are first transformed into the so called build-cata form, then fused via a one-step rewrite rule, the cata-build rule. In the process of the transformation to build-cata form we attempt to replace explicit recursion with a fixed pattern of recursion (catamorphism). We analyse in detail the problem of removing — possibly mutually recursive sets of — polynomial datatypes. We have implemented the warm fusion method in the Glasgow Haskell Compiler, which has allowed practical feedback. One important conclusion is that catamorphisms and fusion in general deserve a more prominent role in the compilation process. We give a detailed measurement of our implementation on a suite of real application programs. Contents Abstract ii 1 Introduction 1 1.1 Contributions................................... 2 1.2 Structureofthethesis . .. .. .. .. .. .. .. .. 3 2 State of the Art in Intermediate Data Structure Removal 5 2.1 Wadler’s schema deforestation . ..... 7 2.2 Therulesandstrategiesapproach. ..... 9 2.3 Listlessnessanddeforestation . ...... 10 2.4 Cheapdeforestation .............................. 12 2.5 Supercompilation................................ 13 2.6 WarmFusion ................................... 13 2.7 Warm Fusion (almost) without inlining . ...... 14 2.8 HyloFusion.................................... 15 2.9 Deforestationforfree. 16 2.10 Generic program transformation . ..... 16 3 The Theory of Warm Fusion 18 3.1 Preliminaries ................................... 19 3.2 Catamorphisms.................................. 20 3.3 Build........................................ 25 3.4 Thecorrectnessofbuildify. 25 iii Contents iv 4 The Practice of Warm Fusion I: The Basics 27 4.1 Informalintroductiontowarmfusion. ...... 27 4.1.1 Buildifyinformally . 29 4.1.2 Catifyinformally............................. 32 4.2 Definitions..................................... 36 4.3 Overviewofthemethod ............................. 37 4.3.1 Thepreprocessingstage . 38 4.3.2 Firststageoffusion ........................... 39 4.3.3 Buildifydetailed ............................. 41 4.3.4 Catifydetailed .............................. 42 4.3.5 Thesecondstage............................. 44 4.3.6 Cleaningup................................ 44 4.4 Discussion..................................... 44 4.4.1 Do catas deserve a special treatment or should they be ordinary Core bindings? ................................. 45 4.4.2 When should catas, maps and builds be derived? . 46 4.4.3 When to transform functions to build-cata form .......... 48 4.4.4 Buildify-catify vs catify-buildify . ....... 48 4.5 First-orderfusion............................... 49 4.5.1 Derivingmaps .............................. 49 4.5.2 Deriving catas: implementing the cata evaluation rule........ 51 4.5.3 Cata-Corerules.............................. 54 4.5.4 Buildify .................................. 55 4.5.5 Catify ................................... 60 5 The Practice of Warm Fusion II: Extensions 64 5.1 Functions with more than one argument . 64 5.1.1 Avoiding more than one argument . 65 5.1.2 Higher-ordercatas ............................ 67 5.1.3 Buildify .................................. 69 Contents v 5.1.4 Catify ................................... 70 5.1.5 Higher-orderfusion. 73 5.1.6 Static argument transformation . 74 5.2 Mutuallyrecursivedatatypes . 74 5.2.1 Derivingmaps .............................. 76 5.2.2 Derivingcatas .............................. 78 5.2.3 NewCata-Corerules........................... 79 5.2.4 Buildify .................................. 80 5.2.5 Catify ................................... 81 5.3 Thedynamicrewritesystem. 84 5.3.1 Thedetails ................................ 84 5.4 Standardisingargumentordering . ..... 86 5.5 Twopracticalissues .............................. 88 5.5.1 Separatecompilation. 88 5.5.2 Listcomprehensions ........................... 91 6 Measuring Warm Fusion 99 6.1 Measuringwarmfusion ............................. 99 6.2 Whatwewanttomeasure............................ 100 6.3 Howtomeasureit?................................ 101 6.4 Adetailedexample................................ 102 6.5 Thebenchmarks ................................. 117 6.6 Ashortanalysisofthebenchmarks. 117 6.7 Summary ..................................... 120 6.7.1 Thecontrolrun.............................. 120 6.7.2 Normalisedrun.............................. 121 6.7.3 Buildifyonly ............................... 123 6.7.4 Catifyonly ................................ 124 6.8 Conclusions .................................... 129 7 Conclusions and Further Work 136 Contents vi 7.1 FurtherWork................................... 137 7.1.1 Automatically deriving code from types . 137 7.1.2 Special abstract machine for fused programs . 138 7.1.3 Transparency of transformations . 138 7.1.4 Moreaggressiveinlining . 139 7.1.5 Fusion for datatypes with embedded functions . 139 7.1.6 Fegarasstylefolds ............................ 140 7.1.7 Monadicmaps,foldsandfusion. 140 7.1.8 Warmerfusion .............................. 141 A The Framework 142 A.1 Thecompiler(pre-warmfusion). 142 A.2 Thesimplifier................................... 144 A.3 Thecompiler(post-warmfusion) . 146 List of figures 2.1 Theideaofprogramtransformation . .... 6 2.2 Wadler’s algebraic deforestation rules . ......... 8 4.1 Overview of the fusion transformation . ...... 39 4.2 Rules for the interaction of catamorphisms and Core . ......... 55 5.1 Cata-Core rules in the presence of mutually recursive datatypes . 79 5.2 Semantics of Haskell list comprehensions . ........ 92 5.3 Traditional list comprehension desugaring scheme . ........... 93 5.4 Optimal list comprehension desugaring scheme . ........ 98 A.1 Glasgow Haskell Compiler passes . 149 A.2 SyntaxoftheCorelanguage. 150 vii List of tables 2.1 Summaryofdeforestationefforts . .... 7 6.1 Programsoftheimaginarysubset. 117 6.2 Programsofthespectralsubset . 118 6.3 Programs of the spectral subset: the Hartel Benchmarks . .......... 119 6.4 Programsoftherealsubset . 119 6.5 Controlrun: imaginarysubset. 121 6.6 Controlrun: theHartelBenchmarks . 121 6.7 Controlrun:spectralsubset. 122 6.8 Controlrun:therealsubset . 123 6.9 Normalise: imaginarysubset. 123 6.10 Normalise: the Hartel Benchmarks . 124 6.11 Normalise: spectralsubset. 125 6.12 Normalise: therealsubset . 126 6.13 A datatype making buildify too successful . ........ 126 6.14 Buildifyonly: imaginarysubset . 127 6.15 Buildify only: the Hartel Benchmarks . 127 6.16 Buildifyonly: spectralsubset . 128 6.17 Buildifyonly: therealsubset . 129 6.18 Catifyonly: imaginarysubset . 130 6.19 Catifyonly: spectralsubset . 131 6.20 Catify only: the Hartel Benchmarks . 132 6.21 Catifyonly: therealsubset . 132 viii List of tables ix 6.22 Buildify, catify and the cata-build rule: imaginary subset . 133 6.23 Buildify, catify and the cata-build rule: spectralsubset. 134 6.24 Buildify, catify and the cata-build rule: the Hartel Benchmarks . 135 6.25 Buildify, catify and the cata-build rule: therealsubset. 135 A.1 Localtransformations . 145 Acknowledgements I would like to thank my supervisor, Simon Peyton Jones for his support, encouragement, and for answering my endless stream of questions about GHC. I would also like to thank my previous supervisor, Phil Wadler who encouraged me to apply to Glasgow. I spent my second year at the Oregon Graduate Institute (Portland, Oregon). It was a terrible year — both personally and professionally — but this was not entirely their fault. The country, the climate, Rock Creek, and myself also had prominent roles in it. The person I need to thank from this period is John Launchbury who said ’yes’ to a question which, at that time, seemed very important to me. As a consequence of my time in the US (and probably the winter months in Glasgow) I developed a taste for living in sunny places. Thanks to Limsoon Wong of Kent Ridge Digital Laboratories, Singapore for giving me the opportunity to work in Singapore for three months and to discover the pleasures of eating a real mango and laksa. For similar reasons (a fine mixture of sunshine and wild night life), I would like to thank Wai Wong of the Hong Kong Baptist University for the six months I worked there. It was a refreshing break from hacking GHC: I was hacking HOL instead. I would also like to thank my long-suffering officemates, flatmates and all sorts of other people I met for bearing with me during long, dark periods of depression. I know I hurt a lot of them so besides my thanks I would also like to apologise. Special thanks go to Mark Shields, office and flatmate, who actually saved my life. Joy Goodman read the first draft of this thesis and corrected many of my mistakes. Manuel Chakravarty released his haskell.sty for LATEX just in time to let me typeset the code appearing in this thesis. The friendship
Recommended publications
  • NICOLAS WU Department of Computer Science, University of Bristol (E-Mail: [email protected], [email protected])
    Hinze, R., & Wu, N. (2016). Unifying Structured Recursion Schemes. Journal of Functional Programming, 26, [e1]. https://doi.org/10.1017/S0956796815000258 Peer reviewed version Link to published version (if available): 10.1017/S0956796815000258 Link to publication record in Explore Bristol Research PDF-document University of Bristol - Explore Bristol Research General rights This document is made available in accordance with publisher policies. Please cite only the published version using the reference above. Full terms of use are available: http://www.bristol.ac.uk/red/research-policy/pure/user-guides/ebr-terms/ ZU064-05-FPR URS 15 September 2015 9:20 Under consideration for publication in J. Functional Programming 1 Unifying Structured Recursion Schemes An Extended Study RALF HINZE Department of Computer Science, University of Oxford NICOLAS WU Department of Computer Science, University of Bristol (e-mail: [email protected], [email protected]) Abstract Folds and unfolds have been understood as fundamental building blocks for total programming, and have been extended to form an entire zoo of specialised structured recursion schemes. A great number of these schemes were unified by the introduction of adjoint folds, but more exotic beasts such as recursion schemes from comonads proved to be elusive. In this paper, we show how the two canonical derivations of adjunctions from (co)monads yield recursion schemes of significant computational importance: monadic catamorphisms come from the Kleisli construction, and more astonishingly, the elusive recursion schemes from comonads come from the Eilenberg-Moore construction. Thus we demonstrate that adjoint folds are more unifying than previously believed. 1 Introduction Functional programmers have long realised that the full expressive power of recursion is untamable, and so intensive research has been carried out into the identification of an entire zoo of structured recursion schemes that are well-behaved and more amenable to program comprehension and analysis (Meijer et al., 1991).
    [Show full text]
  • A Category Theory Explanation for the Systematicity of Recursive Cognitive
    Categorial compositionality continued (further): A category theory explanation for the systematicity of recursive cognitive capacities Steven Phillips ([email protected]) Mathematical Neuroinformatics Group, National Institute of Advanced Industrial Science and Technology (AIST), Tsukuba, Ibaraki 305-8568 JAPAN William H. Wilson ([email protected]) School of Computer Science and Engineering, The University of New South Wales, Sydney, New South Wales, 2052 AUSTRALIA Abstract together afford cognition) whereby cognitive capacity is or- ganized around groups of related abilities. A standard exam- Human cognitive capacity includes recursively definable con- cepts, which are prevalent in domains involving lists, numbers, ple since the original formulation of the problem (Fodor & and languages. Cognitive science currently lacks a satisfactory Pylyshyn, 1988) has been that you don’t find people with the explanation for the systematic nature of recursive cognitive ca- capacity to infer John as the lover from the statement John pacities. The category-theoretic constructs of initial F-algebra, catamorphism, and their duals, final coalgebra and anamor- loves Mary without having the capacity to infer Mary as the phism provide a formal, systematic treatment of recursion in lover from the related statement Mary loves John. An in- computer science. Here, we use this formalism to explain the stance of systematicity is when a cognizer has cognitive ca- systematicity of recursive cognitive capacities without ad hoc assumptions (i.e., why the capacity for some recursive cogni- pacity c1 if and only if the cognizer has cognitive capacity tive abilities implies the capacity for certain others, to the same c2 (see McLaughlin, 2009). So, e.g., systematicity is evident explanatory standard used in our account of systematicity for where one has the capacity to remove the jokers if and only if non-recursive capacities).
    [Show full text]
  • 301669474.Pdf
    Centrum voor Wiskunde en Informatica Centre for Mathematics and Computer Science L.G.L.T. Meertens Paramorphisms Computer Science/ Department of Algorithmics & Architecture Report CS-R9005 February Dib'I( I, 1fle.'1 Cootrumvoor ~', ;""'" ,,., tn!o.-1 Y.,'~• Am.,t,..-(,';if'! The Centre for Mathematics and Computer Science is a research institute of the Stichting Mathematisch Centrum, which was founded on February 11, 1946, as a nonprofit institution aiming at the promotion of mathematics, com­ puter science, and their applications. It is sponsored by the Dutch Govern­ ment through the Netherlands Organization for the Advancement of Research (N.W.O.). Copyright © Stichting Mathematisch Centrum, Amsterdam Paramorphisms Lambert Meertens CWI, Amsterdam, & University of Utrecht 0 Context This paper is a small contribution in the context of an ongoing effort directed towards the design of a calculus for constructing programs. Typically, the development of a program contains many parts that are quite standard, re­ quiring no invention and posing no intellectual challenge of any kind. If, as is indeed the aim, this calculus is to be usable for constructing programs by completely formal manipulation, a major concern is the amount of labour currently required for such non-challenging parts. On one level this concern can be addressed by building more or less spe­ cialised higher-level theories that can be drawn upon in a derivation, as is usual in almost all branches of mathematics, and good progress is being made here. This leaves us still with much low-level laboriousness, like admin­ istrative steps with little or no algorithmic content. Until now, the efforts in reducing the overhead in low-level formal labour have concentrated on using equational reasoning together with specialised notations to avoid the introduction of dummy variables, in particular for "canned induction" in the form of promotion properties for homomorphisms- which have turned out to be ubiquitous.
    [Show full text]
  • A Note on the Under-Appreciated For-Loop
    A Note on the Under-Appreciated For-Loop Jos´eN. Oliveira Techn. Report TR-HASLab:01:2020 Oct 2020 HASLab - High-Assurance Software Laboratory Universidade do Minho Campus de Gualtar – Braga – Portugal http://haslab.di.uminho.pt TR-HASLab:01:2020 A Note on the Under-Appreciated For-Loop by Jose´ N. Oliveira Abstract This short research report records some thoughts concerning a simple algebraic theory for for-loops arising from my teaching of the Algebra of Programming to 2nd year courses at the University of Minho. Interest in this so neglected recursion- algebraic combinator grew recently after reading Olivier Danvy’s paper on folding over the natural numbers. The report casts Danvy’s results as special cases of the powerful adjoint-catamorphism theorem of the Algebra of Programming. A Note on the Under-Appreciated For-Loop Jos´eN. Oliveira Oct 2020 Abstract This short research report records some thoughts concerning a sim- ple algebraic theory for for-loops arising from my teaching of the Al- gebra of Programming to 2nd year courses at the University of Minho. Interest in this so neglected recursion-algebraic combinator grew re- cently after reading Olivier Danvy’s paper on folding over the natural numbers. The report casts Danvy’s results as special cases of the pow- erful adjoint-catamorphism theorem of the Algebra of Programming. 1 Context I have been teaching Algebra of Programming to 2nd year courses at Minho Uni- versity since academic year 1998/99, starting just a few days after AFP’98 took place in Braga, where my department is located.
    [Show full text]
  • Abstract Nonsense and Programming: Uses of Category Theory in Computer Science
    Bachelor thesis Computing Science Radboud University Abstract Nonsense and Programming: Uses of Category Theory in Computer Science Author: Supervisor: Koen Wösten dr. Sjaak Smetsers [email protected] [email protected] s4787838 Second assessor: prof. dr. Herman Geuvers [email protected] June 29, 2020 Abstract In this paper, we try to explore the various applications category theory has in computer science and see how from this application of category theory numerous concepts in computer science are analogous to basic categorical definitions. We will be looking at three uses in particular: Free theorems, re- cursion schemes and monads to model computational effects. We conclude that the applications of category theory in computer science are versatile and many, and applying category theory to programming is an endeavour worthy of pursuit. Contents Preface 2 Introduction 4 I Basics 6 1 Categories 8 2 Types 15 3 Universal Constructions 22 4 Algebraic Data types 36 5 Function Types 43 6 Functors 52 7 Natural Transformations 60 II Uses 67 8 Free Theorems 69 9 Recursion Schemes 82 10 Monads and Effects 102 11 Conclusions 119 1 Preface The original motivation for embarking on the journey of writing this was to get a better grip on categorical ideas encountered as a student assistant for the course NWI-IBC040 Functional Programming at Radboud University. When another student asks ”What is a monad?” and the only thing I can ex- plain are its properties and some examples, but not its origin and the frame- work from which it comes. Then the eventual answer I give becomes very one-dimensional and unsatisfactory.
    [Show full text]
  • Parametric Polymorphism and Operational Improvement
    Parametric Polymorphism and Operational Improvement JENNIFER HACKETT, University of Nottingham, UK GRAHAM HUTTON, University of Nottingham, UK Parametricity, in both operational and denotational forms, has long been a useful tool for reasoning about program correctness. However, there is as yet no comparable technique for reasoning about program improve- ment, that is, when one program uses fewer resources than another. Existing theories of parametricity cannot be used to address this problem as they are agnostic with regard to resource usage. This article addresses this problem by presenting a new operational theory of parametricity that is sensitive to time costs, which can be used to reason about time improvement properties. We demonstrate the applicability of our theory by showing how it can be used to prove that a number of well-known program fusion techniques are time improvements, including fixed point fusion, map fusion and short cut fusion. CCS Concepts: • Software and its engineering → Functional languages; Polymorphism; • Theory of computation → Operational semantics; Additional Key Words and Phrases: parametricity, improvement theory ACM Reference Format: Jennifer Hackett and Graham Hutton. 2018. Parametric Polymorphism and Operational Improvement. Proc. ACM Program. Lang. 2, ICFP, Article 68 (September 2018), 24 pages. https://doi.org/10.1145/3236763 68 1 INTRODUCTION Parametric polymorphism is everywhere. In typed functional languages, many if not most of the built-in and user-defined functions are parametric. Because of this ubiquity, we must carefully study the properties of parametric functions. Chief among these properties is the abstraction theorem [Reynolds 1983], which shows that any well-typed term must satisfy a property that can be derived uniformly from its type.
    [Show full text]
  • Strong Functional Pearl: Harper's Regular-Expression Matcher In
    Strong Functional Pearl: Harper’s Regular-Expression Matcher in Cedille AARON STUMP, University of Iowa, United States 122 CHRISTOPHER JENKINS, University of Iowa, United States of America STEPHAN SPAHN, University of Iowa, United States of America COLIN MCDONALD, University of Notre Dame, United States This paper describes an implementation of Harper’s continuation-based regular-expression matcher as a strong functional program in Cedille; i.e., Cedille statically confirms termination of the program on all inputs. The approach uses neither dependent types nor termination proofs. Instead, a particular interface dubbed a recursion universe is provided by Cedille, and the language ensures that all programs written against this interface terminate. Standard polymorphic typing is all that is needed to check the code against the interface. This answers a challenge posed by Bove, Krauss, and Sozeau. CCS Concepts: • Software and its engineering ! Functional languages; Recursion; • Theory of compu- tation ! Regular languages. Additional Key Words and Phrases: strong functional programming, regular-expression matcher, programming with continuations, recursion schemes ACM Reference Format: Aaron Stump, Christopher Jenkins, Stephan Spahn, and Colin McDonald. 2020. Strong Functional Pearl: Harper’s Regular-Expression Matcher in Cedille. Proc. ACM Program. Lang. 4, ICFP, Article 122 (August 2020), 25 pages. https://doi.org/10.1145/3409004 1 INTRODUCTION Constructive type theory requires termination of programs intended as proofs under the Curry- Howard isomorphism [Sørensen and Urzyczyn 2006]. The language of types is enriched beyond that of traditional pure functional programming (FP) to include dependent types. These allow the expression of program properties as types, and proofs of such properties as dependently typed programs.
    [Show full text]
  • Recursion Patterns As Hylomorphisms
    Recursion Patterns as Hylomorphisms Manuel Alcino Cunha [email protected] Techn. Report DI-PURe-03.11.01 2003, November PURe Program Understanding and Re-engineering: Calculi and Applications (Project POSI/ICHS/44304/2002) Departamento de Inform´atica da Universidade do Minho Campus de Gualtar — Braga — Portugal DI-PURe-03.11.01 Recursion Patterns as Hylomorphisms by Manuel Alcino Cunha Abstract In this paper we show how some of the recursion patterns typically used in algebraic programming can be defined using hylomorphisms. Most of these def- initions were previously known. However, unlike previous approaches that use fixpoint induction, we show how to derive the standard laws of each recursion pattern by using just the basic laws of hylomorphisms. We also define the accu- mulation recursion pattern introduced by Pardo using a hylomorphism, and use this definition to derive the strictness conditions that characterize this operator in the presence of partiality. All definitions are implemented and exemplified in Haskell. 1 Introduction The exponential growth in the use of computers in the past decades raised important questions about the correctness of software, specially in safety critical systems. Compared to other areas of engineering, software engineers are still very unfamiliar with the mathematical foundations of computation, and tend to approach programming more as (black) art and less as a science [5]. Ideally, final implementations should be calculated from their specifications, using simple laws that relate programs, in the same way we calculate with mathematical expressions in algebra. The calculational approach is particular appealing in the area of functional programming, since referential transparency ensures that expressions in func- tional programs behave as ordinary expressions in mathematics.
    [Show full text]
  • A Category Theory Primer
    A category theory primer Ralf Hinze Computing Laboratory, University of Oxford Wolfson Building, Parks Road, Oxford, OX1 3QD, England [email protected] http://www.comlab.ox.ac.uk/ralf.hinze/ 1 Categories, functors and natural transformations Category theory is a game with objects and arrows between objects. We let C, D etc range over categories. A category is often identified with its class of objects. For instance, we say that Set is the category of sets. In the same spirit, we write A 2 C to express that A is an object of C. We let A, B etc range over objects. However, equally, if not more important are the arrows of a category. So, Set is really the category of sets and total functions. (There is also Rel, the category of sets and relations.) If the objects have additional structure (monoids, groups etc.) then the arrows are typically structure-preserving maps. For every pair of objects A; B 2 C there is a class of arrows from A to B, denoted C(A; B). If C is obvious from the context, we abbreviate f 2 C(A; B) by f : A ! B. We will also loosely speak of A ! B as the type of f . We let f , g etc range over arrows. For every object A 2 C there is an arrow id A 2 C(A; A), called the identity. Two arrows can be composed if their types match: if f 2 C(A; B) and g 2 C(B; C ), then g · f 2 C(A; C ).
    [Show full text]
  • Lambda Jam 2018-05-22 Amy Wong
    Introduction to Recursion schemes Lambda Jam 2018-05-22 Amy Wong BRICKX [email protected] Agenda • My background • Problem in recursion • Fix point concept • Recursion patterns, aka morphisms • Using morphisms to solve different recursion problems • References of further reading • Q & A My background • Scala developer • Basic Haskell knowledge • Not familiar with Category Theory • Interested in Functional Programming Recursion is ubiquitous, however, recusive calls are also repeatedly made Example 1 - expression data Expr = Const Int | Add Expr Expr | Mul Expr Expr eval :: Expr -> Int eval (Const x) = x eval (Add e1 e2) = eval e1 + eval e2 eval (Mul e1 e2) = eval e1 * eval e2 Evaluate expression > e = Mul ( Mul (Add (Const 3) (Const 0)) (Add (Const 3) (Const 2)) ) (Const 3) > eval e > 45 Example 2 - factorial factorial :: Int -> Int factorial n | n < 1 = 1 | otherwise = n * factorial (n - 1) > factorial 6 > 720 Example 3 - merge sort mergeSort :: Ord a => [a] -> [a] mergeSort = uncurry merge . splitList where splitList xs | length xs < 2 = (xs, []) | otherwise = join (***) mergeSort . splitAt (length xs `div` 2) $ xs > mergeSort [1,2,3,3,2,1,-10] > [-10,1,1,2,2,3,3] Problem • Recursive call repeatedly made and mix with the application-specific logic • Factoring out the recursive call makes the solution simpler Factor out recursion • Recursion is iteration of nested structures • If we identify abstraction of nested structure • Iteration on abstraction is factored out as pattern • We only need to define non-recursive function for application
    [Show full text]
  • Constructively Characterizing Fold and Unfold*
    Constructively Characterizing Fold and Unfold? Tjark Weber1 and James Caldwell2 1 Institut fur¨ Informatik, Technische Universit¨at Munchen¨ Boltzmannstr. 3, D-85748 Garching b. Munchen,¨ Germany [email protected] 2 Department of Computer Science, University of Wyoming Laramie, Wyoming 82071-3315 [email protected] Abstract. In this paper we formally state and prove theorems charac- terizing when a function can be constructively reformulated using the recursion operators fold and unfold, i.e. given a function h, when can a function g be constructed such that h = fold g or h = unfold g? These results are refinements of the classical characterization of fold and unfold given by Gibbons, Hutton and Altenkirch in [6]. The proofs presented here have been formalized in Nuprl's constructive type theory [5] and thereby yield program transformations which map a function h (accom- panied by the evidence that h satisfies the required conditions), to a function g such that h = fold g or, as the case may be, h = unfold g. 1 Introduction Under the proofs-as-programs interpretation, constructive proofs of theorems re- lating programs yield \correct-by-construction" program transformations. In this paper we formally prove constructive theorems characterizing when a function can be formulated using the recursion operators fold and unfold, i.e. given a func- tion h, when does there exist (constructively) a function g such that h = fold g or h = unfold g? The proofs have been formalized in Nuprl's constructive type theory [1, 5] and thereby yield program transformations which map a function h { accompanied by the evidence that h satisfies the required conditions { to a function g such that h = fold g or, as the case may be, h = unfold g.
    [Show full text]
  • Problem Set 3
    Problem Set 3 IAP 2020 18.S097: Programming with Categories Due Friday January 31 Good academic practice is expected. In particular, cooperation is encouraged, but assignments must be written up alone, and collaborators and resources consulted must be acknowledged. We suggest that you attempt all problems, but we do not expect all problems to be solved. We expect some to be easier if you have more experience with mathematics, and others if you have more experience with programming. The problems in this problem set are in general a step more difficult than those in previous problem sets. Nonetheless, the guideline remains that five problems is a good number to attempt, write up, and submit as homework. Question 1. Pullbacks and limits. Products and terminal objects are examples of limits. Another example is the f g pullback. Let C be a category, and let X −! A − Y be a pair of morphisms in C. The f g pullback of X −! A − Y is an object X ×A Y and a pair of morphisms π1 : X ×A Y ! X and π2 : X ×A Y ! Y such that for all commuting squares C h X k f Y g A there is a unique map u: C ! X ×A Y such that C h u π1 X ×A Y X k π2 f Y g A commutes. We'll think about pullbacks in the category Set of sets and functions. ! ! (a) What is the pullback of the diagram N −! 1 − B? (b) What is the pullback of the diagram X −!! 1 −! Y ? 1 isEven yes (c) What is the pullback of the diagram N −−−−! B −− 1? Here N is the set of natural numbers B = fyes; nog, and isEven: N ! B answers the question \Is n even?".
    [Show full text]