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

Size: px
Start display at page:

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

Transcription

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

2 Data Recursion Genericity Schemes Expression Problem Rank-N Polymorphism Monads GADTs DSLs Type Type Families Classes Effect Free Handlers Theorems

3 Data Recursion Genericity Schemes Expression Problem Rank-N Polymorphism Monads GADTs DSLs Type Type Families Classes Effect Free Handlers Theorems

4 Unstructured Recursion

5 Recursion fac :: Int -> Int fac n = if n == 0 then 1 else fac (n - 1)

6 Recursion fac :: Int -> Int fac n = if n == 0 then 1 else fac (n - 1)

7 Explicit Recursion fac = fix fac

8 Explicit Recursion non-recursive definition fac = fix fac

9 Explicit Recursion non-recursive definition fac = fix fac generic fixpoint combinator

10 Non-Recursive Version fac' :: (Int -> Int) > (Int -> Int) fac f n = if n == 0 then 1 else f (n - 1) 1 level of the recursion

11 Non-Recursive Version fac' :: (Int -> Int) > (Int -> Int) fac f n = if n == 0 then 1 else f (n - 1) 1 level of the recursion parameter for the other levels

12 Non-Recursive Version fac' :: (Int -> Int) > (Int -> Int) fac f n = if n == 0 then 1 else f (n - 1) 1 level of the recursion parameter for the other levels

13 Fixpoint Combinator fix :: (a -> a) -> a fix f = f (fix f) = f (f (fix f)) = f (f (f (fix f))) = f (f (f (f )))

14 Fixpoint Combinator expression with hole fix :: (a -> a) -> a fix f = f (fix f) = f (f (fix f)) = f (f (f (fix f))) = f (f (f (f )))

15 Fixpoint Combinator expression with hole hole plugged with itself fix :: (a -> a) -> a fix f = f (fix f) = f (f (fix f)) = f (f (f (fix f))) = f (f (f (f )))

16 Fixpoint Combinator expression with hole hole plugged with itself fix :: (a -> a) -> a fix f = f (fix f) = f (f (fix f)) = f (f (f (fix f))) = f (f (f (f )))

17 Fixpoint Combinator expression with hole hole plugged with itself fix :: (a -> a) -> a fix f = f (fix f) = f (f (fix f)) = f (f (f (fix f))) = f (f (f (f )))

18 Fixpoint Combinator expression with hole hole plugged with itself fix :: (a -> a) -> a fix f = f (fix f) = f (f (fix f)) = f (f (f (fix f))) = f (f (f (f )))

19 Fixpoint Combinator expression with hole hole plugged with itself fix :: (a -> a) -> a fix f = f (fix f) = f (f (fix f)) = f (f (f (fix f))) f all the way down = f (f (f (f )))

20 General Recursion fix :: (a -> a) -> a fix f = f (fix f)

21 General Recursion fix :: (a -> a) -> a fix f = f (fix f) makes language Turing complete

22 General Recursion fix :: (a -> a) -> a fix f = f (fix f) can express all recursion makes language Turing complete

23 General Recursion Considered Harmful

24 General Recursion Considered Harmful loop = fix id

25 General Recursion Considered Harmful loop = fix id diverge = fix go where go f n = f (n+1)

26 General Recursion Considered Harmful loop = fix id Easy to go over the egde diverge = fix go where go f n = f (n+1)

27 Recursion Schemes

28 A railing to hold on to data List = Nil Cons Int List

29 A railing to hold on to data List = Nil Cons Int List No irregular syntax

30 A railing to hold on to data List = Nil Cons Int List No irregular syntax No type parameter

31 A railing to hold on to Keeping things simple data List = Nil Cons Int List No irregular syntax No type parameter

32 Recursion follows Recursion sum Nil = 0 sum (Cons x xs) = x + sum xs data List = Nil Cons Int List

33 Sliding down the railing sum Nil = 0 sum (Cons x xs) = x + sum xs prod Nil = 1 prod (Cons x xs) = x * prod xs

34 Sliding down the railing sum Nil = 0 sum (Cons x xs) = x + sum xs prod Nil = 1 prod (Cons x xs) = x * prod xs

35 Sliding down the railing sum Nil = 0 sum (Cons x xs) = x + sum xs prod Nil = 1 prod (Cons x xs) = x * prod xs

36 Fold Recursion Scheme sum Nil = 0 sum (Cons x xs) = x + sum xs prod Nil = 1 prod (Cons x xs) = x * prod xs Abstract fold n c Nil = n fold n c (Cons x xs) = c x (fold n c xs)

37 Fold Recursion Scheme sum Nil = 0 sum (Cons x xs) = x + sum xs prod Nil = 1 prod (Cons x xs) = x * prod xs Abstract fold n c Nil = n fold n c (Cons x xs) = c x (fold n c xs)

38 Fold Recursion Scheme sum Nil = 0 sum (Cons x xs) = x + sum xs prod Nil = 1 prod (Cons x xs) = x * prod xs Abstract fold n c Nil = n fold n c (Cons x xs) = c x (fold n c xs)

39 Fold Recursion Scheme sum = fold 0 (+) prod = fold 1 (*) fold n c Nil = n fold n c (Cons x xs) = c x (fold n c xs)

40 Structured Recursion fold n c Nil = n fold n c (Cons x xs) = c x (fold n c xs)

41 Structured Recursion fold n c Nil = n fold n c (Cons x xs) = c x (fold n c xs) Recursion follows list structure

42 Structured Recursion fold n c Nil = n fold n c (Cons x xs) = c x (fold n c xs) Recursion follows list structure Recursive call over recursive list

43 Structured Recursion fold n c Nil = n fold n c (Cons x xs) = c x (fold n c xs) Recursion follows list structure Recursive call over recursive list Terminates (for finite list)

44 Recursive Types

45 Explicit Recursion fac = fix fac

46 Explicit Recursion non-recursive definition fac = fix fac

47 Explicit Recursion non-recursive definition fac = fix fac generic fixpoint combinator

48 Explicit Recursion fac = fix fac

49 Explicit Recursion fac = fix fac List <~> Fix List

50 Explicit Recursion fac = fix fac List <~> Fix List generic fixpoint combinator

51 Explicit Recursion fac = fix fac non-recursive definition List <~> Fix List generic fixpoint combinator

52 Fixpoint Combinator fix :: (a -> a) -> a fix f = f (fix f)

53 Fixpoint Combinator fix :: (a -> a) -> a fix f = f (fix f)

54 Fixpoint Combinator fix :: (a -> a) -> a fix f = f (fix f) -- Fix :: (* -> *) -> * type Fix f = f (Fix f)

55 Fixpoint Combinator fix :: (a -> a) -> a fix f = f (fix f) Recursive Type Synonyms not supported -- Fix :: (* -> *) -> * type Fix f = f (Fix f)

56 Fixpoint Combinator fix :: (a -> a) -> a fix f = f (fix f) -- Fix :: (* -> *) -> * data Fix f = In (f (Fix f))

57 Non-Recursive Version -- List :: * data List = Nil Cons Int List

58 Non-Recursive Version -- List :: * data List = Nil Cons Int List -- List :: * -> * data List r = Nil Cons Int r

59 Isomorphism iso :: List <~> Fix List iso = Iso t f where t Nil = In Nil t (Cons x xs) = In (Cons x (t xs)) f (In Nil ) = Nil f (In (Cons x xs)) = Cons x (f xs)

60 Generic Fold

61 What fold does Cons 1 (Cons 2 (Cons 3 Nil))) fold 0 (+)

62 What fold does Cons 1 (Cons 2 (Cons 3 Nil))) (+) 1 ((+) 2 ((+) 3 0 ))) fold 0 (+)

63 What fold does Cons 1 (Cons 2 (Cons 3 Nil))) (+) 1 ((+) 2 ((+) 3 0 ))) fold 0 (+)

64 What fold does Cons 1 (Cons 2 (Cons 3 Nil))) (+) 1 ((+) 2 ((+) 3 0 ))) fold 0 (+)

65 The Type of Fold fold :: a -> (Int -> a -> a) -> List -> a fold n c Nil = n fold n c (Cons x xs) = c x (fold n c xs)

66 The Type of Fold fold :: a -> (Int -> a -> a) -> List -> a fold n c Nil = n fold n c (Cons x xs) = c x (fold n c xs)

67 The List Algebra

68 The List Algebra a -> (Int -> a -> a) ->

69 The List Algebra a -> (Int -> a -> a) -> <~>

70 The List Algebra a -> (Int -> a -> a) -> <~> a * (Int -> a -> a) ->

71 The List Algebra a -> (Int -> a -> a) -> <~> a * (Int -> a -> a) -> <~>

72 The List Algebra a -> (Int -> a -> a) -> <~> a * (Int -> a -> a) -> <~> (One -> a) * (Int -> a -> a) ->

73 The List Algebra a -> (Int -> a -> a) -> <~> a * (Int -> a -> a) -> <~> (One -> a) * (Int -> a -> a) -> <~>

74 The List Algebra a -> (Int -> a -> a) -> <~> a * (Int -> a -> a) -> <~> (One -> a) * (Int -> a -> a) -> <~> (One -> a) * (Int * a -> a) ->

75 The List Algebra a -> (Int -> a -> a) -> <~> a * (Int -> a -> a) -> <~> (One -> a) * (Int -> a -> a) -> <~> (One -> a) * (Int * a -> a) -> <~>

76 The List Algebra a -> (Int -> a -> a) -> <~> a * (Int -> a -> a) -> <~> (One -> a) * (Int -> a -> a) -> <~> (One -> a) * (Int * a -> a) -> <~> ((One + Int * a) -> a) ->

77 The List Algebra a -> (Int -> a -> a) -> <~> a * (Int -> a -> a) -> <~> (One -> a) * (Int -> a -> a) -> <~> (One -> a) * (Int * a -> a) -> <~> ((One + Int * a) -> a) -> <~>

78 The List Algebra a -> (Int -> a -> a) -> <~> a * (Int -> a -> a) -> <~> (One -> a) * (Int -> a -> a) -> <~> (One -> a) * (Int * a -> a) -> <~> ((One + Int * a) -> a) -> <~> (List a -> a) ->

79 Towards Generic Fold fold :: a -> (Int -> a -> a) -> List -> a fold n c Nil = n fold n c (Cons x xs) = c x (fold n c xs)

80 Towards Generic Fold fold :: (List a -> a) -> List -> a fold alg Nil = alg Nil fold alg (Cons x xs) = alg (Cons x (fold alg xs))

81 Towards Generic Fold fold :: (List a -> a) -> Fix List -> a fold alg (In Nil ) = alg Nil fold alg (In (Cons x xs)) = alg (Cons x (fold alg xs))

82 Functor class Functor f where fmap :: (r -> s) -> (f r -> f s) instance Functor List where fmap f Nil = Nil fmap f (Cons x r) = Cons x (f r)

83 Towards Generic Fold fold :: (List a -> a) -> Fix List -> a fold alg (In s) = alg (fmap (fold alg) s)

84 Generic Fold fold :: Functor f => (f a -> a) -> Fix f -> a fold alg (In s) = alg (fmap (fold alg) s)

85 Example data Exp = Lit Int Add Exp Exp data Exp r = Lit Int Add r r instance Functor Exp where fmap f (Lit n) = Lit n fmap f (Add e1 e2) = Add (f e1) (f e2)

86 Example eval :: Fix Exp -> Int eval = fold alg where alg :: Exp Int -> Int alg (Lit n) = n alg (Add x y) = x + y

87 Example Add Add Lit 3 Lit 1 Lit 2

88 Example Add Add Lit 3 1 2

89 Example Add 3 3

90 Example 6

91 Summary

92 Fold Unstructured Recursion powerful dangerous Structured Recursion with Fold safe often expressive enough datatype generic concept

93 More to Learn Fold fusion parallel fold fusion fold / build fusion deforestation Other recursion schemes

94 Parallel Fold average :: List Float -> Float average l = sum l / length l

95 Parallel Fold average :: List Float -> Float average l = fold 0 (+) l / fold 0 (\_ y -> 1 + y) l

96 Parallel Fold Fusion average :: List Float -> Float average l = uncurry (/) (fold nil cons l) where nil = (0,0) cons x (s,l) = (x + s, 1 + l)

97 Enabling Fusion Jasper Van der Jeugt GHC compiler pipeline of recursive functions

98 Enabling Fusion Jasper Van der Jeugt GHC compiler pipeline of recursive functions compiler plugin

99 Enabling Fusion Jasper Van der Jeugt GHC compiler pipeline of recursive functions compiler plugin folds/builds

100 Enabling Fusion Jasper Van der Jeugt GHC compiler pipeline of recursive functions compiler plugin folds/builds fold/build fusion

101 Enabling Fusion Jasper Van der Jeugt GHC compiler pipeline of recursive functions compiler plugin folds/builds fold/build fusion tight loop

102 Enabling Fusion Jasper Van der Jeugt GHC compiler pipeline of recursive functions compiler plugin folds/builds fold/build fusion tight loop better.io, Zurich

103 Fast Monads for Free You GHC compiler stack of monads

104 Fast Monads for Free You GHC compiler stack of monads compiler plugin

105 Fast Monads for Free You GHC compiler stack of monads compiler plugin folds/builds

106 Fast Monads for Free You GHC compiler stack of monads compiler plugin folds/builds fold/build fusion

107 Fast Monads for Free You GHC compiler stack of monads compiler plugin folds/builds fold/build fusion tight loop

108 Fast Monads for Free You GHC compiler stack of monads compiler plugin folds/builds $$$ fold/build fusion tight loop

109 catamorphism Cata-morphism

110 catamorphism Cata-morphism Greek: down

111 catamorphism Cata-morphism Greek: down Category theory: structure-preserving function

112 slide from Nicolas Wu catamorphism ZOO OF MORPHISMS

113 slide from Nicolas Wu catamorphism anamorphism ZOO OF MORPHISMS

114 slide from Nicolas Wu catamorphism anamorphism apomorphism ZOO OF MORPHISMS

115 slide from Nicolas Wu m catamorphis anamo rphism paramorphis ZOO OF MORPHISMS m s i h p r o apom m

116 slide from Nicolas Wu m catamorphis anamo rphism paramorphis ZOO OF MORPHISMS m s i h p r o apom mutumorphi sm m

117 slide from Nicolas Wu m catamorphis anamo rphism paramorphis ZOO OF MORPHISMS m s i h p r o apom mutumorphi sm zygomorphism m

118 slide from Nicolas Wu m anamo rphism catamorphis paramorphis ZOO OF MORPHISMS m s i h p r o apom histomorp hism mutumorphi sm zygomorphism m

119 slide from Nicolas Wu m anamo rphism catamorphis paramorphis ZOO OF MORPHISMS m s i h p r o apom histomorp hism mutumorphi sm dynamor zygomorphism phism m

120 slide from Nicolas Wu m anamo rphism catamorphis paramorphis ZOO OF MORPHISMS m m s i h p r o apom histomorp hism m s i h p r o m u t fu mutumorphi sm dynamor zygomorphism phism

121 slide from Nicolas Wu m anamo rphism catamorphis paramorphis ZOO OF MORPHISMS m m s i h p r o apom histomorp hism ism h p r o m o r p e r p ic h zygohistomorp m s i h p r o m u t fu mutumorphi sm dynamor zygomorphism phism

122 Next time: 21/4/2015

123 Data Recursion Genericity Schemes Expression Problem Monads GADTs DSLs Type Type Families Classes Monoids and Effect Free other Handlers Theorems Algebras

124 Data Recursion Genericity Schemes Expression Problem Monads GADTs DSLs Type Type Families Classes Monoids and Effect Free other Handlers Theorems Algebras

125 Join the Google Group Leuven Haskell User Group

Advanced Type System Features Tom Schrijvers. Leuven Haskell User Group

Advanced Type System Features Tom Schrijvers. Leuven Haskell User Group Advanced Type System Features Tom Schrijvers Leuven Haskell User Group Data Recursion Genericity Schemes Expression Problem Monads GADTs DSLs Type Type Families Classes Lists and Effect Free Other Handlers

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

Introduction to Recursion schemes

Introduction to Recursion schemes Introduction to Recursion schemes Lambda Jam 2018-05-22 Amy Wong BRICKX amy@brickx.com Agenda My background Problem in recursion Fix point concept Recursion patterns, aka morphisms Using morphisms to solve

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

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

Haskell Type Constraints Unleashed

Haskell Type Constraints Unleashed Haskell Type Constraints Unleashed Dominic Orchard University of Cambridge Tom Schrijvers KU Leuven Fun in the Afternoon, Standard Chartered. February 17, 2010 C τ Type classestype classes Data types Type

More information

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

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

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

Applicatives Comparisons (2C) Young Won Lim 3/6/18

Applicatives Comparisons (2C) Young Won Lim 3/6/18 Comparisons (2C) Copyright (c) 2016-2018 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

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

Shared Subtypes. Subtyping Recursive Parameterized Algebraic Data Types

Shared Subtypes. Subtyping Recursive Parameterized Algebraic Data Types Shared Subtypes Subtyping Recursive Parameterized Algebraic Data Types Ki Yung Ahn kya@cs.pdx.edu Tim Sheard sheard@cs.pdx.edu Department of Computer Science Maseeh College of Engineering & Computer Science

More information

Lecture 8: Summary of Haskell course + Type Level Programming

Lecture 8: Summary of Haskell course + Type Level Programming Lecture 8: Summary of Haskell course + Type Level Programming Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense October 31, 2017 Principles from Haskell

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

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

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

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 Fernandes 1 Alberto Pardo 2 João Saraiva 1 1 Departmento de Informática Universidade do Minho Portugal 2 Instituto de Computación Universidad

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

Advances in Programming Languages

Advances in Programming Languages T O Y H Advances in Programming Languages APL8: Multiparameter Type Classes, Constructor Classes Ian Stark School of Informatics The University of Edinburgh Thursday 4 February Semester 2 Week 4 E H U

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

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

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

Type families and data kinds

Type families and data kinds Type families and data kinds AFP Summer School Wouter Swierstra 1 Today How do GADTs work? Kinds beyond * Programming with types 2 Calling functions on vectors Given two vectors xs : Vec a n and ys : Vec

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

Type Classes in Haskell Tom Schrijvers. Leuven Haskell User Group

Type Classes in Haskell Tom Schrijvers. Leuven Haskell User Group Type Classes in Haskell Tom Schrijvers Leuven Haskell User Group Haskell Research Team Partners Monads Type Classes GHC Folds Pattern Matching Equational Reasoning DSLs Advanced Types Adhoc Overloading

More information

Modular Reifiable Matching

Modular Reifiable Matching Modular Reifiable Matching A List-of-Functors Approach to Two-Level Types Bruno C. d. S. Oliveira University of Hong Kong bruno@cs.hku.hk Shin-Cheng Mu Academia Sinica scm@iis.sinica.edu.tw Shu-Hung You

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

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

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

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

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

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

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

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

GADTs. Wouter Swierstra. Advanced functional programming - Lecture 7. Faculty of Science Information and Computing Sciences GADTs Advanced functional programming - Lecture 7 Wouter Swierstra 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:

More information

Programming in Omega Part 1. Tim Sheard Portland State University

Programming in Omega Part 1. Tim Sheard Portland State University Programming in Omega Part 1 Tim Sheard Portland State University Tim Sheard Computer Science Department Portland State University Portland, Oregon PSU PL Research at Portland State University The Programming

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 12 Functions and Data Types in Haskell 1/45 Programming Paradigms Unit 12 Functions and Data Types in Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

More information

Advanced Functional Programming

Advanced Functional Programming Advanced Functional Programming Tim Sheard Polymorphism Hindley-Milner Polymorphism Rank 2 polymorphism Tim Sheard 1 Polymorphism A function is polymorphic if it can work on any kind of argument. f x =

More information

Introduction to ML. Based on materials by Vitaly Shmatikov. General-purpose, non-c-like, non-oo language. Related languages: Haskell, Ocaml, F#,

Introduction to ML. Based on materials by Vitaly Shmatikov. General-purpose, non-c-like, non-oo language. Related languages: Haskell, Ocaml, F#, Introduction to ML Based on materials by Vitaly Shmatikov slide 1 ML General-purpose, non-c-like, non-oo language Related languages: Haskell, Ocaml, F#, Combination of Lisp and Algol-like features (1958)

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

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

Inductive Types for Free

Inductive Types for Free Inductive Types for Free Representing Nested Inductive Types using W-types Michael Abbott (U. Leicester) Thorsten Altenkirch (U. Nottingham) Neil Ghani (U. Leicester) Inductive Types for Free p.1/22 Ideology

More information

CS153: Compilers Lecture 15: Local Optimization

CS153: Compilers Lecture 15: Local Optimization CS153: Compilers Lecture 15: Local Optimization Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Project 4 out Due Thursday Oct 25 (2 days) Project 5 out Due Tuesday Nov 13 (21 days)

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

Background Type Classes (1B) Young Won Lim 6/28/18

Background Type Classes (1B) Young Won Lim 6/28/18 Background Type Classes (1B) Copyright (c) 2016-2017 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

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

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

CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

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

A Simple Supercompiler Formally Verified in Coq

A Simple Supercompiler Formally Verified in Coq A Simple Supercompiler Formally Verified in Coq IGE+XAO Balkan 4 July 2010 / META 2010 Outline 1 Introduction 2 3 Test Generation, Extensional Equivalence More Realistic Language Use Information Propagation

More information

Generic Constructors and Eliminators from Descriptions

Generic Constructors and Eliminators from Descriptions DRAFT Generic Constructors and Eliminators from Descriptions Type Theory as a Dependently Typed Internal DSL Larry Diehl Tim Sheard Portland State University {ldiehl,sheard}@cs.pdx.edu Abstract Dependently

More information

Advanced Programming Handout 7. Monads and Friends (SOE Chapter 18)

Advanced Programming Handout 7. Monads and Friends (SOE Chapter 18) Advanced Programming Handout 7 Monads and Friends (SOE Chapter 18) The Type of a Type In previous chapters we discussed: Monomorphic types such as Int, Bool, etc. Polymorphic types such as [a], Tree a,

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

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

Giving Haskell a Promotion

Giving Haskell a Promotion Giving Haskell a Promotion José Pedro Magalhães Joint work with Brent A. Yorgey Stephanie Weirich Julien Cretin Simon Peyton Jones Dimitrios Vytiniotis http://www.dreixel.net FP dag 2012, Universiteit

More information

Algebraic Types. Chapter 14 of Thompson

Algebraic Types. Chapter 14 of Thompson Algebraic Types Chapter 14 of Thompson Types so far Base types Int, Integer, Float, Bool, Char Composite types: tuples (t 1,t 2,,t n ) lists [t 1 ] functions (t 1 -> t 2 ) Algebraic types enumerated, product

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

Laying Tiles Ornamentally

Laying Tiles Ornamentally Thesis for the Degree of Licentiate of Engineering Laying Tiles Ornamentally An approach to structuring container traversals Nikita Frolov Department of Computer Science and Engineering Chalmers University

More information

Witnessing Purity, Constancy and Mutability APLAS Ben Lippmeier Australian National University 2009/12/14

Witnessing Purity, Constancy and Mutability APLAS Ben Lippmeier Australian National University 2009/12/14 Witnessing Purity, Constancy and Mutability APLAS 2009 Ben Lippmeier Australian National University 2009/12/14 The hidden cost of state monads map :: (a -> b) -> List a -> List b map f xs = case xs of

More information

Dependent Polymorphism. Makoto Hamana

Dependent Polymorphism. Makoto Hamana 1 Dependent Polymorphism Makoto Hamana Department of Computer Science, Gunma University, Japan http://www.cs.gunma-u.ac.jp/ hamana/ This Talk 2 [I] A semantics for dependently-typed programming [II] A

More information

First-Class Type Classes

First-Class Type Classes First-Class Type Classes Matthieu Sozeau Joint work with Nicolas Oury LRI, Univ. Paris-Sud - Démons Team & INRIA Saclay - ProVal Project Gallium Seminar November 3rd 2008 INRIA Rocquencourt Solutions for

More information

Functional Pearl: A Smart View on Datatypes

Functional Pearl: A Smart View on Datatypes Functional Pearl: A Smart View on Datatypes Mauro Jaskelioff Exequiel Rivas CIFASIS-CONICET, Argentina Universidad Nacional de Rosario, Argentina jaskelioff@cifasis-conicet.gov.ar rivas@cifasis-conicet.gov.ar

More information

Simple Unification-based Type Inference for GADTs

Simple Unification-based Type Inference for GADTs Simple Unification-based Type Inference for GADTs Stephanie Weirich University of Pennsylvania joint work with Dimitrios Vytiniotis, Simon Peyton Jones and Geoffrey Washburn Overview Goal: Add GADTs to

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

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

Interleaving data and effects

Interleaving data and effects Under consideration for publication in J. Functional Programming 1 Interleaving data and effects ROBERT ATKEY University of Strathclyde PATRICIA JOHANN Appalachian State University (e-mail: robert.atkey@strath.ac.uk,

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

Programming Languages Lecture 14: Sum, Product, Recursive Types

Programming Languages Lecture 14: Sum, Product, Recursive Types CSE 230: Winter 200 Principles of Programming Languages Lecture 4: Sum, Product, Recursive Types The end is nigh HW 3 No HW 4 (= Final) Project (Meeting + Talk) Ranjit Jhala UC San Diego Recap Goal: Relate

More information

GADTs. GADTs in Haskell

GADTs. GADTs in Haskell GADTs GADTs in Haskell ADT vs GADT Algebraic Datatype Data List a = Nil Cons a (List a) Data Tree a b = Tip a Node (Tree a b) b Fork (Tree a b) (Tree a b) Note that types than can be expressed as an ADT

More information

Introduction to Functional Programming and Haskell. Aden Seaman

Introduction to Functional Programming and Haskell. Aden Seaman Introduction to Functional Programming and Haskell Aden Seaman Functional Programming Functional Programming First Class Functions Expressions (No Assignment) (Ideally) No Side Effects Different Approach

More information

Box-and-arrow Diagrams

Box-and-arrow Diagrams Box-and-arrow Diagrams 1. Draw box-and-arrow diagrams for each of the following statements. What needs to be copied, and what can be referenced with a pointer? (define a ((squid octopus) jelly sandwich))

More information

List Functions, and Higher-Order Functions

List Functions, and Higher-Order Functions List Functions, and Higher-Order Functions Björn Lisper Dept. of Computer Science and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ List Functions, and Higher-Order

More information

Less Is More. Generic Programming Theory and Practice. José Pedro Magalhães

Less Is More. Generic Programming Theory and Practice. José Pedro Magalhães Less Is More Generic Programming Theory and Practice José Pedro Magalhães Promotoren: Co-promotor: Prof.dr. J.T. Jeuring Prof.dr. S.D. Swierstra Dr. A. Löh This work has been supported by the Fundação

More information

Compilation à la Carte

Compilation à la Carte Compilation à la Carte Laurence E. Day Functional Programming Laboratory University of Nottingham led@cs.nott.ac.uk Graham Hutton Functional Programming Laboratory University of Nottingham graham.hutton@nottingham.ac.uk

More information

Advanced features of Functional Programming (Haskell)

Advanced features of Functional Programming (Haskell) Advanced features of Functional Programming (Haskell) Polymorphism and overloading January 10, 2017 Monomorphic and polymorphic types A (data) type specifies a set of values. Examples: Bool: the type of

More information

Recursive Types and Subtyping

Recursive Types and Subtyping Recursive Types and Subtyping #1 One-Slide Summary Recursive types (e.g., list) make the typed lambda calculus as powerful as the untyped lambda calculus. If is a subtype of then any expression of type

More information

Introduction to Co-Induction in Coq

Introduction to Co-Induction in Coq August 2005 Motivation Reason about infinite data-structures, Reason about lazy computation strategies, Reason about infinite processes, abstracting away from dates. Finite state automata, Temporal logic,

More information

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder Outline 1 2 3 4 What is Haskell? Haskell is a functional programming language. Characteristics functional non-strict ( lazy ) pure (no side effects*) strongly statically typed available compiled and interpreted

More information

Generic Views on Data Types

Generic Views on Data Types Generic Views on Data Types Stefan Holdermans Johan Jeuring Andres Löh Institute of Information and Computing Sciences Utrecht University, P.O. Box 80.089 3508 TB Utrecht, the Netherlands {stefan,johanj,andres}@cs.uu.nl

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

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

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

Polymorphism Overview (1A) Young Won Lim 2/20/18

Polymorphism Overview (1A) Young Won Lim 2/20/18 Polymorphism Overview (1A) Copyright (c) 2016-2017 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

More information

Programming with Universes, Generically

Programming with Universes, Generically Programming with Universes, Generically Andres Löh Well-Typed LLP 24 January 2012 An introduction to Agda Agda Functional programming language Static types Dependent types Pure (explicit effects) Total

More information

Software System Design and Implementation

Software System Design and Implementation Software System Design and Implementation Functional Programming Gabriele Keller The University of New South Wales School of Computer Science and Engineering Sydney, Australia COMP3141 16s1 Course software

More information

Many Holes in Hindley-Milner

Many Holes in Hindley-Milner Many Holes in Hindley-Milner Sam Lindley Laboratory for Foundations of Computer Science, University of Edinburgh Sam.Lindley@ed.ac.uk September 21, 2008 Plugging many-holed contexts : context(3) Plugging

More information

Background Type Classes (1B) Young Won Lim 6/14/18

Background Type Classes (1B) Young Won Lim 6/14/18 Background Type Classes (1B) Copyright (c) 2016-2017 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

More information

Program generation for schema-based, typed data access

Program generation for schema-based, typed data access Program generation for schema-based, typed data access Ralf Lämmel Software Engineer Facebook, London Program generation A use case at Facebook Purpose of generation: typed data access ("O/R mapping" et

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 14/ Prof. Andrea Corradini Department of Computer Science, Pisa Introduc;on to Hakell Lesson 27! 1 The origins: ML programming

More information

Polymorphic Contexts FP-Dag 2015

Polymorphic Contexts FP-Dag 2015 Polymorphic Contexts FP-Dag 2015 Doaitse Swierstra January 14, 2015 Goal of this Talk To show you: that lazy evaluation requires a type system which extend beyond system-f how the Utrecht Haskell Compiler

More information

Reasoning with the HERMIT

Reasoning with the HERMIT Reasoning with the HERMIT Tool Support for Equational Reasoning on GHC Core Programs Andrew Farmer Information and Telecommunication Technology Center University of Kansas, USA afarmer@ittc.ku.edu Neil

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

Fastest Lambda First. Neil Mitchell.

Fastest Lambda First. Neil Mitchell. Fastest Lambda First λ Neil Mitchell www.cs.york.ac.uk/~ndm/ The Problem Count the number of lines in a file = 0 test = 1 test\n = 1 test\ntest = 2 Read from the console Using getchar only No buffering

More information

PATH, a Program Transformation System for Haskell

PATH, a Program Transformation System for Haskell PATH, a Program Transformation System for Haskell A Dissertation Presented to the Faculty of the Graduate School of Yale University in Candidacy for the Degree of Doctor of Philosophy by Mark Anders Tullsen

More information

Applying Type-Level and Generic Programming in Haskell

Applying Type-Level and Generic Programming in Haskell Summer School on Generic and Effectful Programming Applying Type-Level and Generic Programming in Haskell Andres Löh, Well-Typed LLP July 4, 2015 Contents 1 Introduction and type-level programming 5 1.1

More information

Universes. Universes for Data. Peter Morris. University of Nottingham. November 12, 2009

Universes. Universes for Data. Peter Morris. University of Nottingham. November 12, 2009 for Data Peter Morris University of Nottingham November 12, 2009 Introduction Outline 1 Introduction What is DTP? Data Types in DTP Schemas for Inductive Families 2 of Data Inductive Types Inductive Families

More information

Optimising Functional Programming Languages. Max Bolingbroke, Cambridge University CPRG Lectures 2010

Optimising Functional Programming Languages. Max Bolingbroke, Cambridge University CPRG Lectures 2010 Optimising Functional Programming Languages Max Bolingbroke, Cambridge University CPRG Lectures 2010 Objectives Explore optimisation of functional programming languages using the framework of equational

More information

Lists. Michael P. Fourman. February 2, 2010

Lists. Michael P. Fourman. February 2, 2010 Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce

More information

Theorem Proving Principles, Techniques, Applications Recursion

Theorem Proving Principles, Techniques, Applications Recursion NICTA Advanced Course Theorem Proving Principles, Techniques, Applications Recursion 1 CONTENT Intro & motivation, getting started with Isabelle Foundations & Principles Lambda Calculus Higher Order Logic,

More information

Formalization of Array Combinators and their Fusion Rules in Coq

Formalization of Array Combinators and their Fusion Rules in Coq BSc Project Christian Kjær Larsen Formalization of Array Combinators and their Fusion Rules in Coq An experience report Supervisor: Martin Elsman June 12, 2017 Abstract There has recently been new large

More information

CIS 194: Homework 6. Due Wednesday, 4 March. Fibonacci numbers. It s all about being lazy.

CIS 194: Homework 6. Due Wednesday, 4 March. Fibonacci numbers. It s all about being lazy. CIS 194: Homework 6 Due Wednesday, 4 March It s all about being lazy. Fibonacci numbers The Fibonacci numbers F n are defined as the sequence of integers, beginning with 1 and 1, where every integer in

More information