Recursion for the Masses

Total Page:16

File Type:pdf, Size:1020Kb

Recursion for the Masses Recursion for the Masses Recursion for the Masses TCS Seminar WS19/20 Christoph Rauch Dec 10, 2019 Recursion for the Masses Introduction of Recursion to Students Early Stage (FAU) students are more or less expected to "know" what recursion is no definition at all in maths classes "Java can do it" plus a definition of what a recursive definition looks like in Java in GDA (now AuD) tail recursion, mutual recursion, divide & conquer similarly "Haskell can do it" in PFP literally recommended to use iteration whenever possible nowadays, students are blessed with ThProg! Recursion for the Masses First Real Contact Theory of Programming We learn that . (inductive) data types are initial algebras to functors initiality provides unique solutions to recursive equations of a certain form; the "recursion scheme" of folds (and, in fact, the more general primitive recursion) there’s a dual concept (namely final coalgebras) for coinductive data first examples of structured recursion not the end of the line! Recursion for the Masses Recursion Schemes Recursion Schemes folds (tear down a structure) unfolds (build up a structure) algebra f a → Fix f → a ↔ coalgebra f a → a → Fix f catamorphism anamorphism f a → a a → f a generalized prepromorphism* postpromorphism* (m f ↝ f m) → (α → f (m β)) … after applying a NatTrans … before applying a NatTrans generalized (f a → a) → (f ↝ f) (a → f a) → (f ↝ f) (f w ↝ w f) → (f (w α) → β) paramorphism* apomorphism* … with primitive recursion … returning a branch or single level f (Fix f ⨯ a) → a a → f (Fix f ∨ a) zygomorphism* g apomorphism … with a helper function (f b → b) → (f (b ⨯ a) → a) (b → f b) → (a → f (b ∨ a)) g histomorphism histomorphism futumorphism g futumorphism … with prev. answers it has given … multiple levels at a time (f h ↝ h f) → (f (w a) → a) (h f ↝ f h) → (a → f (m a)) f (Cofree f a) → a a → f (Free f a) refolds (build up then tear down a structure) algebra g b → (f ↝ g) → coalgebra f a → a → b hylomorphism others cata; ana dynamorphism codynamorphism generalized synchromorphism apply the generalizations for both histo; ana cata; futu the relevant fold and unfold ??? chronomorphism histo; futu exomorphism Elgot algebra coElgot algebra … may short-circuit while building … may short-circuit while tearing ??? cata; a → b ∨ f a a ⨯ g b → b; ana mutumorphism reunfolds (tear down then build up a structure) coalgebra g b → (a → b) → algebra f a → Fix f → Fix g … can refer to each other’s results (f (a ⨯ b) → a) → (f (a ⨯ b) → b) metamorphism generalized ana; cata apply … both … [un]fold Stolen from Edward Kmett’s http://comonad.com/reader/ 2009/recursion-schemes/ These can be combined in various ways. For example, a “zygohistomorphic * This gives rise to a family of related recursion schemes, modeled in recursion-schemes with distributive law prepromorphism” combines the zygo, histo, and prepro aspects into a combinators signature like (f b → b) → (f ↝ f) → (f (w (b ⨯ a)) → a) → Fix f → a a little bit scary but knowing about them can help make code more efficient and safe Recursion for the Masses Recursion Schemes Ban General Recursion using general recursion carelessly = chaos (structured programming : goto) as (recursion schemes : general recursion) [Meijer et al. 2006] Use Schemes Instead enjoy many desirable properties (e.g. fusion, compositionality) expressive, generic, concise Recursion for the Masses Recursion Schemes Ban General Recursion using general recursion carelessly = chaos (structured programming : goto) as (recursion schemes : general recursion) [Meijer et al. 2006] Use Schemes Instead enjoy many desirable properties (e.g. fusion, compositionality) expressive, generic, concise a little bit scary but knowing about them can help make code more efficient and safe Recursion for the Masses Example: ZygomorphismI Task: write function with property f [v,w,x,y,z] = v - (w + (x - (y + z))) first attempt: lengthEven:: [a] -> Bool lengthEven= even. length f[]=0 f (x:xs)= if lengthEven xs thenx- f xs elsex+ f xs Recursion for the Masses Example: ZygomorphismII First, notice that the rhs of f needs access to f xs as well as x and xs there is a scheme for that! paramorphisms – just a fancy name for primitive recursion on inductive data types: para:: (a -> [a] ->b -> b) ->b -> [a] ->b parafz[]=z para f z (x:xs)= f x xs (para f z xs) f= para (\x xs ac -> if lengthEven xs thenx- ac elsex+ ac)0 Recursion for the Masses Example: Zygomorphism III Now . lengthEven is called in each recursive call quadratic algorithm but: both lengthEven and para are catamorphisms (folds): lengthEven= cata (\x p -> not p) True para' f z= snd. cata (\x (xs, acc) -> (x:xs, f x xs acc)) ([], z) Recursion for the Masses Example: ZygomorphismIV Finally . there is a scheme for that! running two folds in parallel, one of which depends on the result of the other, can be done by way of a zygomorphism: zygo:: (a ->b -> b) -> (a ->b ->c -> c) ->b ->c -> [a] ->c zygofgze= snd. cata (\x (p, q) -> (f x p, g x p q)) (z, e) f= zygo (\x p -> not p) (\x e t -> ife thenx-t elsex+ t) True0 Recursion for the Masses Duals and Combinations So far . we’ve only used initial algebras there are duals for final coalgebras, of course however, there are also schemes combining the two how is that even possible? Recursion for the Masses Data = Codata in Hask I Turning a Blind Eye Haskell allows partial functions blurred distinction between data types and codata types allows people to be lazy (no pun intended) "The usual style is to write as if everything is inductive, and if it still works on infinite data, to pat ourselves on the back for using Haskell rather than ML." – Conor McBride Recursion for the Masses Data = Codata in Hask II Hask, the category of Haskell types and functions, is algebraically compact basically CPO initial algebras and final coalgebras coincide opens up a cheap way to develop more recursion schemes but also necessitates some arbitrary choices and a nasty proof theory Recursion for the Masses Example: HylomorphismI The scheme given an F-algebra a and a coalgebra c, morphisms satisfying the equation h = a ◦ Fh ◦ c the so-called hylo scheme morphisms between any two types! The predicament however, unique solutions are not guaranteed, even in Haskell but, canonical solutions exist: hylo::(Functor f) => (f a -> a) -> (c -> f c) ->c ->a hylo alg coalg= cata alg. ana coalg Recursion for the Masses Example: HylomorphismII The example: Merge sort Algorithm 1 recursively divide a list into smaller lists 2 when the recursive calls return, merge the resulting sorted lists into a bigger sorted list Implementation divide-and-conquer algorithms lend themselves to the hylo scheme the functor f models the shape of the recursive calls; here: a binary tree an anamorphism for a coalgebra split builds up the tree and a catamorphism for an algebra merge tears it down again Recursion for the Masses Merge Sort import Data.List import Data.Functor.Foldable(hylo) import qualified Data.List.Ordered asO data Treeab= Empty| Leafa| Nodebb deriving Functor split[]= Empty split [x]= Leafx split xs= let (l, r)= splitAt (length xs `div` 2) xs in Nodelr merge Empty=[] merge(Leaf x)= [x] merge(Node l r)=O.merge l r mergesort:: Orda => [a] -> [a] mergesort= hylo merge split Recursion for the Masses Generalisations Monads and Comonads recall: all schemes work for arbitrary functors (and their associated data types) but there’s no self-respecting Haskell program without monads recursion-schemes takes that into consideration schemes can be lifted to the (co)Kleisli category of a (co)Monad but: requires distributive laws Distributive Laws given monad M and functor F , natural transformation MF ! FM dually for comonads recursion-schemes offers basic laws and combinators to build new ones Recursion for the Masses Monadic Iteration Performing Side-Effects Repeatedly Elgot monad: monad m with iteration operator of signature (a ! m(b + a)) ! (a ! mb) satisfying certain natural axioms every Monad in Hask is Elgot (by enrichment of Kleisli over CPO) Haskell’s loopM has the type signature above more useful/problematic in more specific settings (e.g. languages without general recursion, with hard-wired effects in the background) Recursion for the Masses Moving to Total Programming Totality enables distinction between data and codata removes arbitrary choices in terms of strictness simplifies the proof theory (e.g. e − e = 0 is not always true in Haskell, since e might be ‘?‘) but some recursion schemes are no longer applicable Monads are no longer automatically Elgot we need to ensure productivity in (co)recursive definitions of codata Recursion for the Masses Catamorphisms in AgdaI Agda dependently typed programming language totality ensured by (quite restrictive) positivity and termination checkers General Definition in Haskell, data Muf= In (f (Mu f)) is valid for any functor Agda’s positivity checker rejects this however, initial algebras for polynomial functors can be defined generically data mu_(F: Functor): Set where <_>:[F](mu F) -> mu F Recursion for the Masses Catamorphisms in AgdaII Implementation naive definition of cata fails the termination check! inlining the functor action works once defined, cata can be used without having to trick the termination checker! ... mapFold(F1|x| F2)Ga(x,y)=( mapFold F1 G a x , mapFold F2 G a y) ... What else can we implement? dependent version of catamorphisms [Fu, Selinger 2018] hylomorphisms? Recursion for the Masses Recursive coalgebras Coalgebra-to-algebra morphisms hylo scheme viewed from a different point of view initial algebra doesn’t have to coincide with final coalgebra defers proof obligation to the programmer, but ensures unique iterate [Capretta et al.
Recommended publications
  • Unfold/Fold Transformations and Loop Optimization of Logic Programs
    Unfold/Fold Transformations and Loop Optimization of Logic Programs Saumya K. Debray Department of Computer Science The University of Arizona Tucson, AZ 85721 Abstract: Programs typically spend much of their execution time in loops. This makes the generation of ef®cient code for loops essential for good performance. Loop optimization of logic programming languages is complicated by the fact that such languages lack the iterative constructs of traditional languages, and instead use recursion to express loops. In this paper, we examine the application of unfold/fold transformations to three kinds of loop optimization for logic programming languages: recur- sion removal, loop fusion and code motion out of loops. We describe simple unfold/fold transformation sequences for these optimizations that can be automated relatively easily. In the process, we show that the properties of uni®cation and logical variables can sometimes be used to generalize, from traditional languages, the conditions under which these optimizations may be carried out. Our experience suggests that such source-level transformations may be used as an effective tool for the optimization of logic pro- grams. 1. Introduction The focus of this paper is on the static optimization of logic programs. Speci®cally, we investigate loop optimization of logic programs. Since programs typically spend most of their time in loops, the generation of ef®cient code for loops is essential for good performance. In the context of logic programming languages, the situation is complicated by the fact that iterative constructs, such as for or while, are unavailable. Loops are usually expressed using recursive procedures, and loop optimizations have be considered within the general framework of inter- procedural optimization.
    [Show full text]
  • 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 Right-To-Left Type System for Value Recursion
    1 A right-to-left type system for value recursion 61 2 62 3 63 4 Alban Reynaud Gabriel Scherer Jeremy Yallop 64 5 ENS Lyon, France INRIA, France University of Cambridge, UK 65 6 66 1 Introduction Seeking to address these problems, we designed and imple- 7 67 mented a new check for recursive definition safety based ona 8 In OCaml recursive functions are defined using the let rec opera- 68 novel static analysis, formulated as a simple type system (which we 9 tor, as in the following definition of factorial: 69 have proved sound with respect to an existing operational seman- 10 let rec fac x = if x = 0 then 1 70 tics [Nordlander et al. 2008]), and implemented as part of OCaml’s 11 else x * (fac (x - 1)) 71 type-checking phase. Our check was merged into the OCaml distri- 12 Beside functions, let rec can define recursive values, such as 72 bution in August 2018. 13 an infinite list ones where every element is 1: 73 Moving the check from the middle end to the type checker re- 14 74 let rec ones = 1 :: ones stores the desirable property that compilation of well-typed programs 15 75 Note that this “infinite” list is actually cyclic, and consists of asingle does not go wrong. This property is convenient for tools that reuse 16 76 cons-cell referencing itself. OCaml’s type-checker without performing compilation, such as 17 77 However, not all recursive definitions can be computed. The MetaOCaml [Kiselyov 2014] (which type-checks quoted code) and 18 78 following definition is justly rejected by the compiler: Merlin [Bour et al.
    [Show full text]
  • A Generic Approach to Datatype Persistency in Haskell
    AGeneric Approach to Datatype Persistency in Haskell Sebastiaan Visser MSc Thesis June 20, 2010 INF/SCR-09-60 Center for Software Technology Daily Supervisor: Dept. of Information and Computing Sciences dr. A. Loh¨ Utrecht University Second Supervisor: Utrecht, the Netherlands prof. dr. J.T. Jeuring 2 Abstract Algebraic datatypes in Haskell are a powerful tool to structure application data. Unfortunately, Haskell datatypes can only be used in-memory. When information is too large to fit in application memory or has to survive the running time of a single process, the information has to be marshalled to and from a persistent storage. The current systems available for persistent storage in Haskell all have some drawbacks. Either the structure of these storage systems does not fit the algebraic datatypes of Haskell, or the sys- tems do not allow partial access to the persistent storage. In this document we describe a new storage framework for Haskell that uses generic pro- gramming to allow the persistent storage of a large class of functional data structures. The system allows access to parts of the data structures, this pre- vents reading in the entire data structure when only small parts are needed. Partial access allows the operations on the persistent data structures to run with the same asymptotic running time as their in-memory counterparts. The framework uses a generic annotation system to automatically lift oper- ations on recursive data structures to work on a block based storage heap on disk. The annotation system helps to keep a strict separation between I/O code and the pure operations on functional data structures.
    [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]
  • Functional Programming (ML)
    Functional Programming CSE 215, Foundations of Computer Science Stony Brook University http://www.cs.stonybrook.edu/~cse215 Functional Programming Function evaluation is the basic concept for a programming paradigm that has been implemented in functional programming languages. The language ML (“Meta Language”) was originally introduced in the 1970’s as part of a theorem proving system, and was intended for describing and implementing proof strategies. Standard ML of New Jersey (SML) is an implementation of ML. The basic mode of computation in SML is the use of the definition and application of functions. 2 (c) Paul Fodor (CS Stony Brook) Install Standard ML Download from: http://www.smlnj.org Start Standard ML: Type ''sml'' from the shell (run command line in Windows) Exit Standard ML: Ctrl-Z under Windows Ctrl-D under Unix/Mac 3 (c) Paul Fodor (CS Stony Brook) Standard ML The basic cycle of SML activity has three parts: read input from the user, evaluate it, print the computed value (or an error message). 4 (c) Paul Fodor (CS Stony Brook) First SML example SML prompt: - Simple example: - 3; val it = 3 : int The first line contains the SML prompt, followed by an expression typed in by the user and ended by a semicolon. The second line is SML’s response, indicating the value of the input expression and its type. 5 (c) Paul Fodor (CS Stony Brook) Interacting with SML SML has a number of built-in operators and data types. it provides the standard arithmetic operators - 3+2; val it = 5 : int The Boolean values true and false are available, as are logical operators such as not (negation), andalso (conjunction), and orelse (disjunction).
    [Show full text]
  • Abstract Recursion and Intrinsic Complexity
    ABSTRACT RECURSION AND INTRINSIC COMPLEXITY Yiannis N. Moschovakis Department of Mathematics University of California, Los Angeles [email protected] October 2018 iv Abstract recursion and intrinsic complexity was first published by Cambridge University Press as Volume 48 in the Lecture Notes in Logic, c Association for Symbolic Logic, 2019. The Cambridge University Press catalog entry for the work can be found at https://www.cambridge.org/us/academic/subjects/mathematics /logic-categories-and-sets /abstract-recursion-and-intrinsic-complexity. The published version can be purchased through Cambridge University Press and other standard distribution channels. This copy is made available for personal use only and must not be sold or redistributed. This final prepublication draft of ARIC was compiled on November 30, 2018, 22:50 CONTENTS Introduction ................................................... .... 1 Chapter 1. Preliminaries .......................................... 7 1A.Standardnotations................................ ............. 7 Partial functions, 9. Monotone and continuous functionals, 10. Trees, 12. Problems, 14. 1B. Continuous, call-by-value recursion . ..................... 15 The where -notation for mutual recursion, 17. Recursion rules, 17. Problems, 19. 1C.Somebasicalgorithms............................. .................... 21 The merge-sort algorithm, 21. The Euclidean algorithm, 23. The binary (Stein) algorithm, 24. Horner’s rule, 25. Problems, 25. 1D.Partialstructures............................... ......................
    [Show full text]
  • Generating Mutually Recursive Definitions
    Generating Mutually Recursive Definitions Jeremy Yallop Oleg Kiselyov University of Cambridge, UK Tohoku University, Japan [email protected] [email protected] Abstract let rec s = function A :: r ! s r j B :: r ! t r j [] ! true and t = function A :: r ! s r j B :: r ! u r j [] ! false Many functional programs — state machines (Krishnamurthi and u = function A :: r ! t r j B :: r ! u r j [] ! false 2006), top-down and bottom-up parsers (Hutton and Meijer 1996; Hinze and Paterson 2003), evaluators (Abelson et al. 1984), GUI where each function s, t, and u realizes a recognizer, taking a list of initialization graphs (Syme 2006), &c. — are conveniently ex- A and B symbols and returning a boolean. However, the program pressed as groups of mutually recursive bindings. One therefore that builds such a group from a description of an arbitrary state expects program generators, such as those written in MetaOCaml, machine cannot be expressed in MetaOCaml. to be able to build programs with mutual recursion. The limited support for generating mutual recursion is a con- Unfortunately, currently MetaOCaml can only build recursive sequence of expression-based quotation: brackets enclose expres- groups whose size is hard-coded in the generating program. The sions, and splices insert expressions into expressions — but a group general case requires something other than quotation, and seem- of bindings is not an expression. There is a second difficulty: gen- ingly weakens static guarantees on the resulting code. We describe erating recursive definitions with ‘backward’ and ‘forward’ refer- the challenges and propose a new language construct for assuredly ences seemingly requires unrestricted, Lisp-like gensym, which de- generating binding groups of arbitrary size – illustrating with a col- feats MetaOCaml’s static guarantees.
    [Show full text]
  • Inductively Defined Functions in Functional Programming Languages
    CORE Metadata, citation and similar papers at core.ac.uk Provided by Elsevier - Publisher Connector JOURNAL OF COMPUTER AND SYSTEM SCIENCES 34, 4099421 (1987) Inductively Defined Functions in Functional Programming Languages R. M. BURSTALL Department of Computer Science, University of Edinburgh, King$ Buildings, Mayfield Road, Edinburgh EH9 3JZ, Scotland, U.K. Received December 1985; revised August 1986 This paper proposes a notation for defining functions or procedures in such a way that their termination is guaranteed by the scope rules. It uses an extension of case expressions. Suggested uses include programming languages and logical languages; an application is also given to the problem of proving inequations from initial algebra specifications. 0 1987 Academic Press, Inc. 1. INTRODUCTION When we define recursive functions on natural numbers we can ensure that they terminate without a special proof, by adhering to the schema for primitive recur- sion. The schema can be extended to other data types. This requires inspection of the function definition to ensure that it conforms to such a schema, involving second-order pattern matching. However, if we combine the recursion with a case expression which decomposes elements of the data type we can use the ordinary scoping rules for variables to ensure termination, without imposing any special schema. I formulate this proposal for “inductive” case expressions in ML [S], since it offers succinct data-type definitions and a convenient case expression. Any other functional language with these facilities could do as well. A number of people have advocated the use of initial algebras to define data types in specification languages, see, for example, Goguen, Thatcher and Wagner [3] and Burstall and Goguen [ 11.
    [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]