Introduction to Recursion schemes

Size: px
Start display at page:

Download "Introduction to Recursion schemes"

Transcription

1 Introduction to Recursion schemes Lambda Jam Amy Wong BRICKX

2 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

3 My background Scala developer Basic Haskell knowledge Not familiar with Category Theory Interested in Functional Programming

4 Recursion is ubiquitous, however, recusive calls are also repeatedly made

5 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

6 Evaluate expression > e = Mul ( Mul (Add (Const 3) (Const 0)) (Add (Const 3) (Const 2)) ) (Const 3) > eval e > 45

7 Example 2 - factorial factorial :: Int -> Int factorial n n < 1 = 1 otherwise = n * factorial (n - 1) > factorial 6 > 720

8 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]

9 Problem Recursive call repeatedly made and mix with the application-specific logic Factoring out the recursive call makes the solution simpler

10 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 requirement Problem solved in simple way

11 How?

12 Fix point Higher-kinded type Fix, (* -> *) -> * newtype Fix f = Fix { unfix :: f (Fix f) } Fix f is nested data structure We expect f is not just a type constructor but also a functor

13 Iterate Fix f newtype Fix f = Fix { unfix :: f (Fix f) } f (Fix f) fmap iterate f a unfix alg Fix f iterate a

14 Replace iterate by cata alg Decouples alg from recursion pattern f (Fix f) fmap (cata alg) f a unfix alg Fix f cata alg a

15 cata function cata :: (Functor f) => (f a -> a) -> Fix f -> a cata alg = alg. fmap (cata alg). unfix cata is called catamorphism - fundamental recursion pattern

16 Highlights on catamorphism cata :: (Functor f) => (f a -> a) -> Fix f -> a alg :: f a -> a is called algebra, non-recursive function for application-specific logic a is called carrier of the algebra If we solve a recursion problem using cata, we only need to define functor f and f a -> a according to application requirement

17 Catamorphism example - expression Original ADT data Expr = Const Int Add Expr Expr Mul Expr Expr Re-design the ADT as functor (notice the bolded carrier type) data ExprF a = Const Int Add a a Mul a a deriving Functor

18 Algebra to evaluate expression -- cata :: (Functor f) => (f a -> a) -> Fix f -> a In evaluating an expression, carrier type is Int eval :: ExprF Int -> Int eval (Const c) = c eval (Add x y) = x + y eval (Mul x y) = x * y

19 -- cata :: (Functor f) => (f a -> a) -> Fix f -> a > e = Fix $ Mul (Fix $ Mul (Fix $ Add (Fix $ Const 3) (Fix $ Const 0)) (Fix $ Add (Fix $ Const 3) (Fix $ Const 2)) ) (Fix $ Const 3) > cata eval e > 45

20 Algebra to format expression -- cata :: (Functor f) => (f a -> a) -> Fix f -> a In formatting an expression, carrier type is String format :: ExprF String -> String format (Const c) = show c format (Add s1 s2) = "(" <> s1 <> " + " <> s2 <> ")" format (Mul s1 s2) = s1 <> " * " <> s2 > cata format e > "(3 + 0) * (3 + 2) * 3"

21 But catamorphism can t solve all problems

22 Anamorphism opposite of Catamorphism Catamorphism is building up a value from a nested structure, like a piece of paper folded up to an object Anamorphism is the opposite, like an object unfolded to a piece of paper

23 Anamorphism signature Catamorphism cata :: (Functor f) => (f a -> a) -> Fix f -> a cata alg = alg. fmap (cata alg). unfix Anamorphism ana :: (Functor f) => (a -> f a) -> a -> Fix f ana coalg = Fix. fmap (ana coalg). coalg coalg :: (a -> f a) is called coalgebra

24 Hylomorphism The composition of anamorphism followed by catamorphism hylo :: (Functor f) =>(f b -> b) -> (a -> f a) -> a -> b hylo alg coalg = cata alg. ana coalg Alternatively, eliminating intermediate nested data structure hylo alg coalg = alg. fmap (hylo alg coalg). coalg

25 Hylomorphism example merge sort Original code for 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

26 ADT for merge sort -- (notice that bolded carrier type) data TreeF a r = Empty Leaf a Branch r r deriving Functor

27 Coalgebra for anamorphism -- ana :: (Functor f) => (a -> f a) -> a -> Fix f -- TreeF a is functor, [a] is carrier type split :: Ord a => [a] -> TreeF a [a] split [] = Empty split [x] = Leaf x split xs = uncurry Branch. splitat (length xs `div` 2) $ xs

28 Algebra for catamorphism -- cata :: (Functor f) => (f a -> a) -> Fix f -> a merge_ :: Ord a => TreeF a [a] -> [a] merge_ Empty = [] merge_ (Leaf x) = [x] merge_ (Branch l r) = merge l r

29 -- hylo :: (Functor f) =>(f b -> b) -> (a -> f a) -> a -> b > hylo merge split [1,2,3,3,2,1,-10] > [-10,1,1,2,2,3,3]

30 Paramorphism cata :: (Functor f) => (f a -> a) -> Fix f -> a In catamorphism, (f a -> a) only provides the value a, to be transformed. It doesn t provide the original structure, Fix f from which the value is built. Paramorphism address this problem para :: (Functor f) =>(f (a, Fix f) -> a)-> Fix f -> a para alg = alg. fmap (para alg &&& id). unfix

31 Paramorphism example Original code for factorial factorial n n < 1 = 1 otherwise = n * factorial (n - 1) ADT for the natural number that copes with following conditions Number < 1 Number >= 1 data NatF a = Zero Succ a deriving Functor

32 Use Catamorphism for natural number -- cata :: (Functor f) => (f a -> a) -> Fix f -> a natalg :: NatF Int -> Int natalg Zero = 0 natalg (Succ n) = n + 1

33 Use Paramorphism for factorial number --para :: (Functor f) => (f (a, Fix f) -> a) -> Fix f -> a factalg :: NatF (Int, Fix NatF) -> Int factalg Zero = 1 factalg (Succ (n, x)) = n * cata natalg (Fix $ Succ x) > nat = Fix $ Succ $ Fix $ Succ $ Fix $ Succ $ Fix Zero > para factalg nat > 6

34 Recap Catamorphism cata :: (Functor f) => (f a -> a) -> Fix f -> a Anamorphism ana :: (Functor f) => (a -> f a) -> a -> Fix f Hylomorphism hylo :: (Functor f) =>(f b -> b) -> (a -> f a) -> a -> b Paramorphism para :: (Functor f) => (f (a, Fix f) -> a) -> Fix f -> a

35 Recursion schemes Catamorphism, paramorphism, anamorphism and hylomorphism are fundamental morphisms They are available from Haskell recursion schemes library When using morphisms to solve recursion problems, we only need to consider application-specific requirement by designing ADT for functor and non-recursive function

36 More interesting morphisms More interesting morphisms are available from recursion schemes library More morphisms to be invented by us Try to use morphisms to solve recursion problems to make simple solution

37 References Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire - recursion schemes in Scala

38 Q&A

Functional Programming

Functional Programming or applied deep magic Lectures on Modern Scientific Programming Wigner RCP 23-25 November 2015 Functor A type that has the Functor property comes with a function: called fmap. a b F a F b fmap takes a

More information

The Algebra of Programming in Haskell

The Algebra of Programming in Haskell The Algebra of Programming in Haskell Bruno Oliveira The Algebra of Programming in Haskell p.1/21 Datatype Generic Programming - Motivation/Goals The project is to develop a novel mechanism for parameterizing

More information

Those classes I never wrote. The power of recursion schemes applied to data engineering

Those classes I never wrote. The power of recursion schemes applied to data engineering Those 10000 classes I never wrote The power of recursion schemes applied to data engineering 1 greetings The name s Valentin (@ValentinKasas) Organizer of the Paris Scala User Group Member of the ScalaIO

More information

Lecture 4: Higher Order Functions

Lecture 4: Higher Order Functions Lecture 4: Higher Order Functions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 26, 2017 HIGHER ORDER FUNCTIONS The order of a function

More information

Trees. Solution: type TreeF a t = BinF t a t LeafF 1 point for the right kind; 1 point per constructor.

Trees. Solution: type TreeF a t = BinF t a t LeafF 1 point for the right kind; 1 point per constructor. Trees 1. Consider the following data type Tree and consider an example inhabitant tree: data Tree a = Bin (Tree a) a (Tree a) Leaf deriving Show tree :: Tree Int tree = Bin (Bin (Bin Leaf 1 Leaf ) 2 (Bin

More information

Bringing Functions into the Fold Tom Schrijvers. Leuven Haskell User Group

Bringing Functions into the Fold Tom Schrijvers. Leuven Haskell User Group Bringing Functions into the Fold Tom Schrijvers Leuven Haskell User Group Data Recursion Genericity Schemes Expression Problem Rank-N Polymorphism Monads GADTs DSLs Type Type Families Classes Effect Free

More information

Data types à la carte

Data types à la carte Data types à la carte FP AMS 21/6/18 Wouter Swierstra 1 Warm-up: expressions in Haskell Suppose we re implementing a small expression language in Haskell. We can define a data type for expressions and

More information

INTRODUCTION TO HASKELL

INTRODUCTION TO HASKELL INTRODUCTION TO HASKELL PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2018 Dalhousie University 1/81 HASKELL: A PURELY FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be

More information

Data types à la carte. Wouter Swierstra Dutch HUG 25/8/10

Data types à la carte. Wouter Swierstra Dutch HUG 25/8/10 Data types à la carte Wouter Swierstra Dutch HUG 25/8/10 Expressions data Expr where Add :: Expr -> Expr -> Expr Val :: Int -> Expr eval :: Expr -> Int eval (Val x) = x eval (Add l r) = eval l + eval r

More information

Programming with Math and Logic

Programming with Math and Logic .. Programming with Math and Logic an invitation to functional programming Ed Morehouse Wesleyan University The Plan why fp? terms types interfaces The What and Why of Functional Programming Computing

More information

Stream Fusion. Wouter Swierstra 30/11/2010

Stream Fusion. Wouter Swierstra 30/11/2010 Stream Fusion Wouter Swierstra 30/11/2010 1 Exercise: Write a function that sums the square of all the odd integers between two arguments m and n. 2 Haskell solution f : (Int,Int) -> Int f = sum. map square.

More information

Representing Cyclic Structures as Nested Datatypes. Makoto Hamana

Representing Cyclic Structures as Nested Datatypes. Makoto Hamana Representing Cyclic Structures as Nested Datatypes Makoto Hamana Department of Computer Science, Gunma University, Japan Joint work with Neil Ghani Tarmo Uustalu Varmo Vene U. Nottingham U. Tallinn U.

More information

Isomorphisms, Hylomorphisms and Hereditarily Finite Data Types in Haskell

Isomorphisms, Hylomorphisms and Hereditarily Finite Data Types in Haskell Isomorphisms, Hylomorphisms and Hereditarily Finite Data Types in Haskell 1 1 Department of Computer Science and Engineering Univ of North Texas SAC 09 Motivation Figure : Shapeshifting between datatypes:

More information

Generic Programming with Adjunctions

Generic Programming with Adjunctions Generic Programming with Adjunctions 0.0 Generic Programming with Adjunctions Ralf Hinze Computing Laboratory, University of Oxford Wolfson Building, Parks Road, Oxford, OX1 3QD, England ralf.hinze@comlab.ox.ac.uk

More information

Exercise 1 (2+2+2 points)

Exercise 1 (2+2+2 points) 1 Exercise 1 (2+2+2 points) The following data structure represents binary trees only containing values in the inner nodes: data Tree a = Leaf Node (Tree a) a (Tree a) 1 Consider the tree t of integers

More information

Introduction to Functional Programming in Haskell 1 / 56

Introduction to Functional Programming in Haskell 1 / 56 Introduction to Functional Programming in Haskell 1 / 56 Outline Why learn functional programming? The essence of functional programming What is a function? Equational reasoning First-order vs. higher-order

More information

Programming Language Concepts, CS2104 Lecture 7

Programming Language Concepts, CS2104 Lecture 7 Reminder of Last Lecture Programming Language Concepts, CS2104 Lecture 7 Tupled Recursion Exceptions Types, ADT, Haskell, Components 5th Oct 2007 CS2104, Lecture 7 1 Overview 5th Oct 2007 CS2104, Lecture

More information

Bananas in Space: Extending Fold and Unfold to Exponential Types

Bananas in Space: Extending Fold and Unfold to Exponential Types Bananas in Space: Extending Fold and Unfold to Exponential Types Erik Meijer and Graham Hutton University of Utrecht The Netherlands http://www.cs.ruu.nl/people/{erik,graham}/ Abstract Fold and unfold

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Haskell: Declaring Types and Classes Dr. Hyunyoung Lee 1 Outline Declaring Data Types Class and Instance Declarations 2 Defining New Types Three constructs for defining types:

More information

College Functors, Applicatives

College Functors, Applicatives College 2016-2017 Functors, Applicatives Wouter Swierstra with a bit of Jurriaan Hage Utrecht University Contents So far, we have seen monads define a common abstraction over many programming patterns.

More information

IA014: Advanced Functional Programming

IA014: Advanced Functional Programming IA014: Advanced Functional Programming 8. GADT Generalized Algebraic Data Types (and type extensions) Jan Obdržálek obdrzalek@fi.muni.cz Faculty of Informatics, Masaryk University, Brno Motivation IA014

More information

Catamorphism Generation and Fusion Using Coq

Catamorphism Generation and Fusion Using Coq Catamorphism Generation and Fusion Using Coq Simon Robillard, Univ Orléans, INSA Centre Val de Loire, LIFO EA 4022, Orléans, France, simon.robillard@univ-orleans.fr Abstract Catamorphisms are a class of

More information

CSC324 Principles of Programming Languages

CSC324 Principles of Programming Languages CSC324 Principles of Programming Languages http://mcs.utm.utoronto.ca/~324 November 21, 2018 Last Class Types terminology Haskell s type system Currying Defining types Value constructors Algebraic data

More information

All About Comonads (Part 1) An incomprehensible guide to the theory and practice of comonadic programming in Haskell

All About Comonads (Part 1) An incomprehensible guide to the theory and practice of comonadic programming in Haskell All About Comonads (Part 1) An incomprehensible guide to the theory and practice of comonadic programming in Haskell Edward Kmett http://comonad.com/ Categories Categories have objects and arrows Every

More information

Modular dependent induction in Coq, Mendler-style. Paolo Torrini

Modular dependent induction in Coq, Mendler-style. Paolo Torrini Modular dependent induction in Coq, Mendler-style Paolo Torrini Dept. of Computer Science, KU Leuven ITP 16, Nancy, 22.08.2016 * The Author left the Institution in April 2016 motivation: cost-effective

More information

Logic - CM0845 Introduction to Haskell

Logic - CM0845 Introduction to Haskell Logic - CM0845 Introduction to Haskell Diego Alejandro Montoya-Zapata EAFIT University Semester 2016-1 Diego Alejandro Montoya-Zapata (EAFIT University) Logic - CM0845 Introduction to Haskell Semester

More information

Recursive Types. Chapter 7

Recursive Types. Chapter 7 Chapter 7 Recursive Types By adding special rules for natural numbers to λ, we obtained system T. We may now want to have separate rules for other data structures: lists, binary trees, streams. We can

More information

Sorting with Bialgebras and Distributive Laws

Sorting with Bialgebras and Distributive Laws Sorting with Bialgebras and Distributive Laws Ralf Hinze Daniel W. H. James Thomas Harper Nicolas Wu José Pedro Magalhães Department of Computer Science, University of Oxford {ralf.hinze;daniel.james;tom.harper;nicolas.wu;jose.pedro.magalhaes}@cs.ox.ac.uk

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Final Review Part I Dr. Hyunyoung Lee 1 Programming Language Characteristics Different approaches to describe computations, to instruct computing devices E.g., Imperative,

More information

Type system. Type theory. Haskell type system. EDAN40: Functional Programming Types and Type Classes (revisited)

Type system. Type theory. Haskell type system. EDAN40: Functional Programming Types and Type Classes (revisited) Type system EDAN40: Functional Programming Types and Type Classes (revisited) Jacek Malec Dept. of Computer Science, Lund University, Sweden April 3rd, 2017 In programming languages, a type system is a

More information

INTRODUCTION TO FUNCTIONAL PROGRAMMING

INTRODUCTION TO FUNCTIONAL PROGRAMMING INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham adapted by Gordon Uszkay 1 What is Functional Programming? Opinions differ, and it is difficult to give a precise definition,

More information

Software System Design and Implementation

Software System Design and Implementation Software System Design and Implementation Property-based Testing Gabriele Keller The University of New South Wales School of Computer Science and Engineering Sydney, Australia COMP3141 17s1 Testing in

More information

Parsing. Zhenjiang Hu. May 31, June 7, June 14, All Right Reserved. National Institute of Informatics

Parsing. Zhenjiang Hu. May 31, June 7, June 14, All Right Reserved. National Institute of Informatics National Institute of Informatics May 31, June 7, June 14, 2010 All Right Reserved. Outline I 1 Parser Type 2 Monad Parser Monad 3 Derived Primitives 4 5 6 Outline Parser Type 1 Parser Type 2 3 4 5 6 What

More information

CATEGORICAL PROGRAMMING WITH INDUCTIVE AND COINDUCTIVE TYPES VARMO VENE

CATEGORICAL PROGRAMMING WITH INDUCTIVE AND COINDUCTIVE TYPES VARMO VENE DISSERTATIONES MATHEMATICAE UNIVERSITATIS TARTUENSIS 23 CATEGORICAL PROGRAMMING WITH INDUCTIVE AND COINDUCTIVE TYPES VARMO VENE TARTU 2000 DISSERTATIONES MATHEMATICAE UNIVERSITATIS TARTUENSIS 23 DISSERTATIONES

More information

Haskell Programming with Nested Types: A Principled Approach

Haskell Programming with Nested Types: A Principled Approach Haskell Programming with Nested Types: A Principled Approach Patricia Johann and Neil Ghani ({patricia,ng}@cis.strath.ac.uk) University of Strathclyde, Glasgow, G1 1XH, Scotland Abstract. Initial algebra

More information

Exercise 1 ( = 24 points)

Exercise 1 ( = 24 points) 1 Exercise 1 (4 + 5 + 4 + 6 + 5 = 24 points) The following data structure represents polymorphic binary trees that contain values only in special Value nodes that have a single successor: data Tree a =

More information

JVM ByteCode Interpreter

JVM ByteCode Interpreter JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first

More information

Problem Set CVO 103, Spring 2018

Problem Set CVO 103, Spring 2018 Problem Set CVO 103, Spring 2018 Hakjoo Oh Due: 06/12 (in class) Problem 1 The Fibonacci numbers can be defined as follows: 0 if n = 0 fib(n) = 1 if n = 1 fib(n 1) + fib(n 2) otherwise Write in OCaml the

More information

Applicative, traversable, foldable

Applicative, traversable, foldable Applicative, traversable, foldable Advanced functional programming - Lecture 3 Wouter Swierstra 1 Beyond the monad So far, we have seen how monads define a common abstraction over many programming patterns.

More information

Denotational Semantics. Domain Theory

Denotational Semantics. Domain Theory Denotational Semantics and Domain Theory 1 / 51 Outline Denotational Semantics Basic Domain Theory Introduction and history Primitive and lifted domains Sum and product domains Function domains Meaning

More information

Exercise 1 ( = 18 points)

Exercise 1 ( = 18 points) 1 Exercise 1 (4 + 5 + 4 + 5 = 18 points) The following data structure represents polymorphic binary trees that contain values only in special Value nodes that have a single successor: data Tree a = Leaf

More information

A Library Writer s Guide to Shortcut Fusion

A Library Writer s Guide to Shortcut Fusion A Library Writer s Guide to Shortcut Fusion Thomas Harper Department of Computer Science, University of Oxford tom.harper@cs.ox.ac.uk Abstract There are now a variety of shortcut fusion techniques in the

More information

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without previous written authorization. 1 2 The simplest way to create

More information

INFOB3TC Solutions for the Exam

INFOB3TC Solutions for the Exam Department of Information and Computing Sciences Utrecht University INFOB3TC Solutions for the Exam Johan Jeuring Monday, 13 December 2010, 10:30 13:00 lease keep in mind that often, there are many possible

More information

CSCE 314 Programming Languages Functors, Applicatives, and Monads

CSCE 314 Programming Languages Functors, Applicatives, and Monads CSCE 314 Programming Languages Functors, Applicatives, and Monads Dr. Hyunyoung Lee 1 Motivation Generic Functions A common programming pattern can be abstracted out as a definition. For example: inc ::

More information

Part 20. Sorting and Selection

Part 20. Sorting and Selection Part 20 Sorting and Selection CSCI 3110 Code Summer 2015 1 Introduction Here we implement the different sorting algorithms discussed in class: Insertion Sort, Merge Sort, and the various variants of Quick

More information

Coq Summer School, Session 2 : Basic programming with numbers and lists. Pierre Letouzey

Coq Summer School, Session 2 : Basic programming with numbers and lists. Pierre Letouzey Coq Summer School, Session 2 : Basic programming with numbers and lists Pierre Letouzey Predened data structures Predened types are actually declared to Coq at load time 1 : Inductive bool := true false.

More information

Query Optimization. Query Optimization. Optimization considerations. Example. Interaction of algorithm choice and tree arrangement.

Query Optimization. Query Optimization. Optimization considerations. Example. Interaction of algorithm choice and tree arrangement. COS 597: Principles of Database and Information Systems Query Optimization Query Optimization Query as expression over relational algebraic operations Get evaluation (parse) tree Leaves: base relations

More information

EXTENDED USES OF TEMPLATE META-PROGRAMMING

EXTENDED USES OF TEMPLATE META-PROGRAMMING MAXWELL SWADLING EXTENDED USES OF TEMPLATE META-PROGRAMMING YOW Lambda Jam 2014 EXTENDED META-PROGRAMMING Construct proofs Inference Create extensible data structures Tools: Template Haskell Constraint

More information

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions PROGRAMMING IN HASKELL CS-205 - Chapter 6 - Recursive Functions 0 Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int Int factorial n product

More information

Standard prelude. Appendix A. A.1 Classes

Standard prelude. Appendix A. A.1 Classes Appendix A Standard prelude In this appendix we present some of the most commonly used definitions from the standard prelude. For clarity, a number of the definitions have been simplified or modified from

More information

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

Applicative, traversable, foldable

Applicative, traversable, foldable Applicative, traversable, foldable Advanced functional programming - Lecture 4 Wouter Swierstra and Alejandro Serrano 1 Beyond the monad So far, we have seen how monads define a common abstraction over

More information

Midterm 2. CMSC 430 Introduction to Compilers Fall Instructions Total 100. Name: November 21, 2016

Midterm 2. CMSC 430 Introduction to Compilers Fall Instructions Total 100. Name: November 21, 2016 Name: Midterm 2 CMSC 430 Introduction to Compilers Fall 2016 November 21, 2016 Instructions This exam contains 7 pages, including this one. Make sure you have all the pages. Write your name on the top

More information

Programming Languages Fall 2013

Programming Languages Fall 2013 Programming Languages Fall 2013 Lecture 2: types Prof. Liang Huang huang@qc.cs.cuny.edu Recap of Lecture 1 functional programming vs. imperative programming basic Haskell syntax function definition lazy

More information

Exercise 1 ( = 22 points)

Exercise 1 ( = 22 points) 1 Exercise 1 (4 + 3 + 4 + 5 + 6 = 22 points) The following data structure represents polymorphic lists that can contain values of two types in arbitrary order: data DuoList a b = C a (DuoList a b) D b

More information

A Shortcut Fusion Rule for Circular Program Calculation

A Shortcut Fusion Rule for Circular Program Calculation A Shortcut Fusion Rule for Circular Program Calculation João Paulo Fernandes Universidade do Minho, Portugal jpaulo@di.uminho.pt Alberto Pardo Universidad de la Republica, Uruguay pardo@fing.edu.uy João

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

The Zipper. Ralf Hinze, Johan Jeuring. August??, 2002

The Zipper. Ralf Hinze, Johan Jeuring. August??, 2002 1 The Zipper Ralf Hinze, Johan Jeuring August??, 2002 Introduction 1 The zipper is a data structure that is used to represent a tree together with a subtree that is the focus of attention, where that focus

More information

A general introduction to Functional Programming using Haskell

A general introduction to Functional Programming using Haskell A general introduction to Functional Programming using Haskell Matteo Rossi Dipartimento di Elettronica e Informazione Politecnico di Milano rossi@elet.polimi.it 1 Functional programming in a nutshell

More information

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 08: Type Classes o o Review: What is a type class? Basic Type Classes: Eq, Ord, Enum, Integral,

More information

Haskell Overview II (2A) Young Won Lim 9/26/16

Haskell Overview II (2A) Young Won Lim 9/26/16 (2A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

Chapter 11 - The Countdown Problem

Chapter 11 - The Countdown Problem PROGRAMMING IN HASKELL Chapter 11 - The Countdown Problem 1 What Is Countdown? A popular quiz programme on British television that has been running since 1982. Based upon an original French version called

More information

Haskell Overloading (1) LiU-FP2016: Lecture 8 Type Classes. Haskell Overloading (3) Haskell Overloading (2)

Haskell Overloading (1) LiU-FP2016: Lecture 8 Type Classes. Haskell Overloading (3) Haskell Overloading (2) Haskell Overloading (1) LiU-FP2016: Lecture 8 Type Classes Henrik Nilsson University of Nottingham, UK What is the type of (==)? E.g. the following both work: 1 == 2 a == b I.e., (==) can be used to compare

More information

FUNCTIONAL PEARLS The countdown problem

FUNCTIONAL PEARLS The countdown problem To appear in the Journal of Functional Programming 1 FUNCTIONAL PEARLS The countdown problem GRAHAM HUTTON School of Computer Science and IT University of Nottingham, Nottingham, UK www.cs.nott.ac.uk/

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

GADTs. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 7. [Faculty of Science Information and Computing Sciences]

GADTs. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 7. [Faculty of Science Information and Computing Sciences] GADTs Advanced functional programming - Lecture 7 Wouter Swierstra and Alejandro Serrano 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree

More information

User-Defined Algebraic Data Types

User-Defined Algebraic Data Types 72 Static Semantics User-Defined Types User-Defined Algebraic Data Types An algebraic data type declaration has the general form: data cx T α 1... α k = K 1 τ 11... τ 1k1... K n τ n1... τ nkn introduces

More information

Lambda calculus. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 6

Lambda calculus. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 6 Lambda calculus Advanced functional programming - Lecture 6 Wouter Swierstra and Alejandro Serrano 1 Today Lambda calculus the foundation of functional programming What makes lambda calculus such a universal

More information

Monadic Augment and Generalised Short Cut Fusion

Monadic Augment and Generalised Short Cut Fusion Monadic Augment and Generalised Short Cut Fusion Neil Ghani University of Leicester Leicester LE1 7RH, UK ng13@mcs.le.ac.uk Patricia Johann Rutgers University Camden, NJ 08102, USA pjohann@crab.rutgers.edu

More information

Structural polymorphism in Generic Haskell

Structural polymorphism in Generic Haskell Structural polymorphism in Generic Haskell Andres Löh andres@cs.uu.nl 5 February 2005 Overview About Haskell Genericity and other types of polymorphism Examples of generic functions Generic Haskell Overview

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee 1 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as

More information

Type-indexed functions in Generic Haskell

Type-indexed functions in Generic Haskell Type-indexed functions in Generic Haskell Johan Jeuring September 15, 2004 Introduction Today I will talk about: a Types of polymorphism. b Type-indexed functions. c Dependencies. Read about b, and c in

More information

A Catalogue of Functional Refactorings Version 1

A Catalogue of Functional Refactorings Version 1 A Catalogue of Functional Refactorings Version 1 Simon Thompson, Claus Reinke Computing Laboratory, University of Kent 1 August 2001 Abstract This document is the first draft of a catalogue of refactorings

More information

GADTs. Alejandro Serrano. AFP Summer School. [Faculty of Science Information and Computing Sciences]

GADTs. Alejandro Serrano. AFP Summer School. [Faculty of Science Information and Computing Sciences] GADTs AFP Summer School Alejandro Serrano 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree a) This definition introduces: 3 A datatype data

More information

From natural numbers to the lambda calculus

From natural numbers to the lambda calculus From natural numbers to the lambda calculus Benedikt Ahrens joint work with Ralph Matthes and Anders Mörtberg Outline 1 About UniMath 2 Signatures and associated syntax Outline 1 About UniMath 2 Signatures

More information

Module Title: Informatics 1 Functional Programming (first sitting) Exam Diet (Dec/April/Aug): December 2014 Brief notes on answers:

Module Title: Informatics 1 Functional Programming (first sitting) Exam Diet (Dec/April/Aug): December 2014 Brief notes on answers: Module Title: Informatics 1 Functional Programming (first sitting) Exam Diet (Dec/April/Aug): December 2014 Brief notes on answers: -- Full credit is given for fully correct answers. -- Partial credit

More information

Implementing the Opetopes:

Implementing the Opetopes: Implementing the Opetopes: Programming with Higher Dimensional Trees Eric Finster May 22, 2018 Abstract The opetopes, introduced by Baez and Dolan in [BD97] as a part of their proposed definition of higher

More information

Shell CSCE 314 TAMU. Higher Order Functions

Shell CSCE 314 TAMU. Higher Order Functions 1 CSCE 314: Programming Languages Dr. Dylan Shell Higher Order Functions 2 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as a result.

More information

Building Compilers by Combining Algebras

Building Compilers by Combining Algebras Building Compilers by Combining Algebras Garrin Kimmell Perry Alexander Ed Komp Information and Telecommunications Technology Center Department of Electrical Engineering and Computer Science The University

More information

Graphical Untyped Lambda Calculus Interactive Interpreter

Graphical Untyped Lambda Calculus Interactive Interpreter Graphical Untyped Lambda Calculus Interactive Interpreter (GULCII) Claude Heiland-Allen https://mathr.co.uk mailto:claude@mathr.co.uk Edinburgh, 2017 Outline Lambda calculus encodings How to perform lambda

More information

Quick announcement. Midterm date is Wednesday Oct 24, 11-12pm.

Quick announcement. Midterm date is Wednesday Oct 24, 11-12pm. Quick announcement Midterm date is Wednesday Oct 24, 11-12pm. The lambda calculus = ID (λ ID. ) ( ) The lambda calculus (Racket) = ID (lambda (ID) ) ( )

More information

Programovací jazyky F# a OCaml. Chapter 5. Hiding recursion using function-as-values

Programovací jazyky F# a OCaml. Chapter 5. Hiding recursion using function-as-values Programovací jazyky F# a OCaml Chapter 5. Hiding recursion using function-as-values Hiding the recursive part» Writing recursive functions explicitly let rec sum list = match list with [] -> 0 x::xs ->

More information

Shell CSCE 314 TAMU. Functions continued

Shell CSCE 314 TAMU. Functions continued 1 CSCE 314: Programming Languages Dr. Dylan Shell Functions continued 2 Outline Defining Functions List Comprehensions Recursion 3 A Function without Recursion Many functions can naturally be defined in

More information

The Haskell HOP: Higher-order Programming

The Haskell HOP: Higher-order Programming The Haskell HOP: Higher-order Programming COS 441 Slides 6 Slide content credits: Ranjit Jhala, UCSD Agenda Haskell so far: First-order functions This time: Higher-order functions: Functions as data, arguments

More information

Verification of Selection and Heap Sort Using Locales

Verification of Selection and Heap Sort Using Locales Verification of Selection and Heap Sort Using Locales Danijela Petrović September 19, 2015 Abstract Stepwise program refinement techniques can be used to simplify program verification. Programs are better

More information

Haskell through HUGS THE BASICS

Haskell through HUGS THE BASICS Haskell through HUGS THE BASICS FP for DB Basic HUGS 1 Algorithmic Imperative Languages variables assignment if condition then action1 else action2 loop block while condition do action repeat action until

More information

The Worker/Wrapper Transformation

The Worker/Wrapper Transformation The Worker/Wrapper Transformation Andy Gill 1 Graham Hutton 2 1 Galois, Inc. 2 University of Nottingham February 6, 2008 Andy Gill, Graham Hutton The Worker/Wrapper Transformation February 6, 2008 1 /

More information

Fission for Program Comprehension

Fission for Program Comprehension Fission for Program Comprehension Jeremy Gibbons Oxford University Computing Laboratory Wolfson Building, Parks Road, Oxford OX1 3QD, UK http://www.comlab.ox.ac.uk/jeremy.gibbons/ Abstract. Fusion is a

More information

Introduction to Functional Programming using Haskell

Introduction to Functional Programming using Haskell Introduction to Functional Programming using Haskell Errata April 7, 1999 Chapter 1 page 3, line 1 Replace? square 14198724 by? square 14197824. page 9, line 14 Replace hit the the interrupt key by hit

More information

CSE Programming Languages Midterm - Winter 2010

CSE Programming Languages Midterm - Winter 2010 CSE 341 - Programming Languages Midterm - Winter 2010 Your Name: Open book and notes. No laptop computers, PDAs, internet-equipped cellphones, or similar devices. Please answer the problems on the exam

More information

Advanced Functional Programming

Advanced Functional Programming Advanced Functional Programming Tim Sheard Portland State University Lecture 2: More about Type Classes Implementing Type Classes Higher Order Types Multi-parameter Type Classes Tim Sheard 1 Implementing

More information

Modular Executable Language Specifications in Haskell

Modular Executable Language Specifications in Haskell Modular Executable Language Specifications in Haskell Mirjana Ivanović mira@unsim.ns.ac.yu Viktor Kunčak viktor@uns.ns.ac.yu Institute of Mathematics, Novi Sad Abstract We propose a framework for specification

More information

Programming Languages 3. Definition and Proof by Induction

Programming Languages 3. Definition and Proof by Induction Programming Languages 3. Definition and Proof by Induction Shin-Cheng Mu Oct. 22, 2015 Total Functional Programming The next few lectures concerns inductive definitions and proofs of datatypes and programs.

More information

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values. Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421d # true;; - : bool = true # false;; - : bool =

More information

Arrow Basics. Ted Cooper CS510 Winter Here s a literate introduction to arrows and review of the basic Arrow typeclasses.

Arrow Basics. Ted Cooper CS510 Winter Here s a literate introduction to arrows and review of the basic Arrow typeclasses. Arrow Basics Ted Cooper theod@pdx.edu CS510 Winter 2016 1 Introduction Here s a literate introduction to arrows and review of the basic Arrow typeclasses. {-# LANGUAGE Arrows #-} module ArrowBasics where

More information

The Art of Recursion: Problem Set 10

The Art of Recursion: Problem Set 10 The Art of Recursion: Problem Set Due Tuesday, November Tail recursion A recursive function is tail recursive if every recursive call is in tail position that is, the result of the recursive call is immediately

More information

Parallelism; Parallel Collections

Parallelism; Parallel Collections Parallelism; Parallel Collections COS 326 Andrew W. Appel Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel let x = 1 + 2 in 3 + x Visualizing Computational Costs Visualizing

More information

GENERIC SELECTIONS OF SUBEXPRESSIONS

GENERIC SELECTIONS OF SUBEXPRESSIONS GENERIC SELECTIONS OF SUBEXPRESSIONS Martijn van Steenbergen MSc Thesis June 6, 2010 INF/SCR-09-61 Center for Software Technology Dept. of Information and Computing Sciences Utrecht University Utrecht,

More information