Generic Programming with Adjunctions

Size: px
Start display at page:

Download "Generic Programming with Adjunctions"

Transcription

1 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 March 2010 University of Oxford Ralf Hinze 1-172

2 Generic Programming with Adjunctions 1.0 Part 1 Prologue University of Oxford Ralf Hinze 2-172

3 Generic Programming with Adjunctions Outline 1. What? 2. Why? 3. Where? 4. Overview University of Oxford Ralf Hinze 3-172

4 Generic Programming with Adjunctions What? What? Haskell programmers have embraced functors, natural transformations, initial algebras, final coalgebras, monads,... It is time to turn our attention to adjunctions. University of Oxford Ralf Hinze 4-172

5 Generic Programming with Adjunctions Why? Catamorphism f = b f in = b F f University of Oxford Ralf Hinze 5-172

6 Generic Programming with Adjunctions Why? Banana-split law h k = h F outl k F outr University of Oxford Ralf Hinze 6-172

7 Generic Programming with Adjunctions Why? Proof of banana-split law ( h k ) in = { split-fusion } h in k in = { fold-computation } h F h k F k = { split-computation } h F (outl ( h k )) k F (outr ( h k )) = { F functor } h F outl F ( h k ) k F outr F ( h k ) = { split-fusion } (h F outl k F outr) F ( h k ) University of Oxford Ralf Hinze 7-172

8 Generic Programming with Adjunctions Why? Example: total data Stack = Empty Push (Nat, Stack) total : Stack Nat total (Empty) = 0 total (Push (n, s)) = n + total s University of Oxford Ralf Hinze 8-172

9 Generic Programming with Adjunctions Why? Two-level types Abstracting away from the recursive call. data Stack stack = Empty Push (Nat, stack) instance Functor Stack where fmap f (Empty) = Empty fmap f (Push (n, s)) = Push (n, f s) Tying the recursive knot. newtype µf = In {in : f (µf )} type Stack = µstack University of Oxford Ralf Hinze 9-172

10 Generic Programming with Adjunctions Why? Two-level functions Structure. total : Stack Nat Nat total (Empty) = 0 total (Push (n, s)) = n + s Tying the recursive knot. total : µstack Nat total (In s) = total (fmap total s) University of Oxford Ralf Hinze

11 Generic Programming with Adjunctions Why? Counterexample: stack stack : (Stack, Stack) Stack stack (Empty, bs) = bs stack (Push (a, as), bs) = Push (a, stack (as, bs)) University of Oxford Ralf Hinze

12 Generic Programming with Adjunctions Why? Counterexamples: fac and fib data Nat = Z S Nat fac : Nat Nat fac (Z) = 1 fac (S n) = S n fac n fib : Nat Nat fib (Z) = Z fib (S Z) = S Z fib (S (S n)) = fib n + fib (S n) University of Oxford Ralf Hinze

13 Generic Programming with Adjunctions Why? Counterexample: sum data List a = Nil Cons (a, List a) sum : List Nat Nat sum (Nil) = 0 sum (Cons (a, as)) = a + sum as University of Oxford Ralf Hinze

14 Generic Programming with Adjunctions Why? Counterexample: append append : a. (List a, List a) List a append (Nil, bs) = bs append (Cons (a, as), bs) = Cons (a, append (as, bs)) University of Oxford Ralf Hinze

15 Generic Programming with Adjunctions Why? Counterexample: concat concat : a. List (List a) List a concat (Nil) = Nil concat (Cons (l, ls)) = append (l, concat ls) University of Oxford Ralf Hinze

16 Generic Programming with Adjunctions Where? References The lectures are based on: Part 1: R. Hinze: A category theory primer, SSGIP Part 2 & 3: R. Hinze: Adjoint Folds and Unfolds, MPC 10. Part 4: R. Hinze: Type Fusion. Further reading: S. Mac Lane: Categories for the Working Mathematician. M. Fokkinga, L. Meertens: Adjunctions. R. Bird, R. Paterson: Generalised folds for nested datatypes. University of Oxford Ralf Hinze

17 Generic Programming with Adjunctions Overview Overview Part 0: Prologue Part 1: Category theory Part 2: Adjoint folds and unfolds Part 3: Adjunctions Part 4: Application: Type fusion Part 5: Epilogue University of Oxford Ralf Hinze

18 Generic Programming with Adjunctions 2.0 Part 2 Category theory University of Oxford Ralf Hinze

19 Generic Programming with Adjunctions Outline 5. Categories, functors and natural transformations 6. Constructions on categories 7. Initial and final objects 8. Products 9. Adjunctions 10. Yoneda lemma University of Oxford Ralf Hinze

20 Generic Programming with Adjunctions Categories, functors and natural transformations Category objects: A C, arrows: f C(A, B), identity: id A C(A, A), composition: if f C(A, B) and g C(B, C), then g f C(A, C), is associative with id as its neutral element. University of Oxford Ralf Hinze

21 Generic Programming with Adjunctions Categories, functors and natural transformations Example: a preorder P objects: a P, arrows: a b, identity: a a (reflexivity), composition: if a b and b c, then a c (transitivity). NB There is at most one arrow between two objects. University of Oxford Ralf Hinze

22 Generic Programming with Adjunctions Categories, functors and natural transformations Example: Set objects: sets, arrows: total functions, identity: id x = x, composition: function composition (g f ) x = g (f x). University of Oxford Ralf Hinze

23 Generic Programming with Adjunctions Categories, functors and natural transformations Example: Mon objects: monoids A, ɛ, +, arrows: monoid homomorphisms h : A, 0, + B, 1, : h 0 = 1 h (x + y) = h x h y, identity: id x = x, composition: function composition (g f ) x = g (f x). University of Oxford Ralf Hinze

24 Generic Programming with Adjunctions Categories, functors and natural transformations Functor F : C D, action on objects, action on arrows, if f C(A, B), then F f D(F A, F B) F id A = id F A, F (g f ) = F g F f. University of Oxford Ralf Hinze

25 Generic Programming with Adjunctions Categories, functors and natural transformations Example: the forgetful functor U : Mon Set, action on objects: U A, ɛ, + = A, action on arrows: U f = f. University of Oxford Ralf Hinze

26 Generic Programming with Adjunctions Categories, functors and natural transformations Natural transformation let F, G : C D be two parallel functors, a transformation α : F G is a collection of arrows: for each object A C there is an arrow α A D(F A, G A), a natural transformation α : F G additionally satisfies G h α A = α B F h for all arrows h C(A, B). F A F h F B α A G A G h G B α B University of Oxford Ralf Hinze

27 Generic Programming with Adjunctions Constructions on categories Cat objects: small categories, arrows: functors, identity: identity functor: Id C A = A and Id C f = f, composition: (G F) A = G (F A) and (G F) f = G (F f ). University of Oxford Ralf Hinze

28 Generic Programming with Adjunctions Constructions on categories Functor category D C let C and D be two categories, objects: functors C D, arrows: natural transformations F G, identity: id F A = id F A, composition: (β α) A = β A α A. University of Oxford Ralf Hinze

29 Generic Programming with Adjunctions Constructions on categories Opposite category C op let C be a category, objects: A C op if A C arrows: f C op (A, B) if f C(B, A) identity: id A C(A, A), composition: g f C op (A, C) if f g C(C, A). University of Oxford Ralf Hinze

30 Generic Programming with Adjunctions Constructions on categories Product category C 1 C 2 let C 1 and C 2 be two categories, objects: A 1, A 2 C 1 C 2 if A 1 C 1 and A 2 C 2, arrows: f 1, f 2 (C 1 C 2 )( A 1, A 2, B 1, B 2 ) if f 1 C 1 (A 1, B 1 ) and f 2 C 2 (A 2, B 2 ), identity: id = id, id, composition: g 1, g 2 f 1, f 2 = g 1 f 1, g 2 f 2. University of Oxford Ralf Hinze

31 Generic Programming with Adjunctions Constructions on categories Outl, Outr and projection functors: Outl : C D C; Outl A, B = A; Outl f, g = f ; Outr : C D D; Outr A, B = B; Outr f, g = g. diagonal functor: : C C C; A = A, A ; f = f, f. University of Oxford Ralf Hinze

32 Generic Programming with Adjunctions Constructions on categories The hom-functor C(, =) : C op C Set, action on objects: C(, =) A, B = C(A, B), action on arrows: C(, =) f, g = λ h. g h f, shorthand: C(f, g) h = g h f. University of Oxford Ralf Hinze

33 Generic Programming with Adjunctions Initial and final objects Initial object The object 0 is initial if for each object B C there is exactly one arrow from 0 to B, denoted B (pronounce gnab ). 0 B B University of Oxford Ralf Hinze

34 Generic Programming with Adjunctions Initial and final objects Final object Dually, 1 is a final object if for each object A C there is a unique arrow from A to 1, denoted! A (pronounce bang ). A! A 1 University of Oxford Ralf Hinze

35 Generic Programming with Adjunctions Products Product The product of two objects B 1 and B 2 consists of an object written B 1 B 2, a pair of arrows outl : B 1 B 2 B 1 and outr : B 1 B 2 B 2, and satisfies the following universal property: for each object A, for each pair of arrows f 1 : A B 1 and f 2 : A B 2, there exists an arrow f 1 f 2 : A B 1 B 2 such that f 1 = outl g f 2 = outr g f 1 f 2 = g, for all g : A B 1 B 2. University of Oxford Ralf Hinze

36 Generic Programming with Adjunctions Products Product A f 1 B 1 outl. f 1 f 2. B 1 B 2 f 2 outr B 2 University of Oxford Ralf Hinze

37 Generic Programming with Adjunctions Products Laws computation laws: f 1 = outl (f 1 f 2 ); f 2 = outr (f 1 f 2 ), reflection law: outl outr = id A B. University of Oxford Ralf Hinze

38 Generic Programming with Adjunctions Products Laws fusion law: (f 1 f 2 ) h = f 1 h f 2 h, action of on arrows: f 1 f 2 = f 1 outl f 2 outr, functor fusion law: (k 1 k 2 ) (f 1 f 2 ) = k 1 f 1 k 2 f 2, outl and outr are natural transformations: k 1 outl = outl (k 1 k 2 ); k 2 outr = outr (k 1 k 2 ). University of Oxford Ralf Hinze

39 Generic Programming with Adjunctions Products Proof of functor fusion (k 1 k 2 ) (f 1 f 2 ) = { definition of } (k 1 outl k 2 outr) (f 1 f 2 ) = { fusion } k 1 outl (f 1 f 2 ) k 2 outr (f 1 f 2 ) = { computation } k 1 f 1 k 2 f 2 University of Oxford Ralf Hinze

40 Generic Programming with Adjunctions Products Naturality fusion and functor fusion: ( ) : A B. (C C)( A, B) C(A, B), naturality of outl and outr: outl : B. C( B, Outl B); outr : B. C( B, Outr B), or more succinctly outl, outr : B. (C C)( ( B), B). University of Oxford Ralf Hinze

41 Generic Programming with Adjunctions Adjunctions Adjunction C L R D φ : A B. C(L A, B) D(A, R B) University of Oxford Ralf Hinze

42 Generic Programming with Adjunctions Adjunctions Adjoints, adjuncts and units left and right adjoints: L g = φ (η g), R f = φ (f ɛ), left and right adjuncts: φ g = ɛ L g, φ f = R f η, counit and unit: ɛ = φ id, η = φ id. University of Oxford Ralf Hinze

43 Generic Programming with Adjunctions Adjunctions Adjoints of the diagonal functor f = outl, outr g f = g C + C C C f = g f inl, inr = g University of Oxford Ralf Hinze

44 Generic Programming with Adjunctions Adjunctions Left adjoint of the forgetful functor Mon List U Set University of Oxford Ralf Hinze

45 Generic Programming with Adjunctions Adjunctions 2.5 φ introduction / elimination φ elimination / introduction Universal property f = φ g φ f = g ɛ : C(L (R B), B) η : D(A, R (L A)) ɛ = φ id φ id = η / computation law computation law / η-rule / β-rule β-rule / η-rule f = φ (φ f ) φ (φ g) = g reflection law / / reflection law simple η-rule / simple β-rule simple β-rule / simple η-rule id = φ η φ ɛ = id University of Oxford Ralf Hinze

46 Generic Programming with Adjunctions Adjunctions 2.5 φ introduction / elimination φ elimination / introduction Universal property f = φ g φ f = g functor fusion law / / fusion law φ is natural in A φ is natural in A φ g L h = φ (g h) φ f h = φ (f L h) fusion law / / functor fusion law φ is natural in B φ is natural in B k φ g = φ (R k g) R k φ f = φ (k f ) ɛ is natural in B η is natural in A k ɛ = ɛ L (R k) R (L h) η = η h University of Oxford Ralf Hinze

47 Generic Programming with Adjunctions Yoneda lemma Yoneda lemma Let H : C Set be a functor, and let B C be an object. H B C(B, ) H The functions witnessing the isomorphism are φ s = λ κ. H κ s, φ α = α B id B. NB Continuation-passing style is a special case: H = C(A, ). University of Oxford Ralf Hinze

48 Generic Programming with Adjunctions 3.0 Part 3 Adjoint folds and unfolds University of Oxford Ralf Hinze

49 Generic Programming with Adjunctions Outline 11. Semantics of datatypes 12. Mendler-style folds and unfolds 13. Adjoint folds and unfolds University of Oxford Ralf Hinze

50 Generic Programming with Adjunctions Semantics of datatypes Example: total data Stack = Empty Push (Nat, Stack) total : Stack Nat total (Empty) = 0 total (Push (n, s)) = n + total s University of Oxford Ralf Hinze

51 Generic Programming with Adjunctions Semantics of datatypes Fixed-point equations both Stack and total are given by recursion equations, meaning of x = Ψ x? a solves the equation iff a is a fixed point of Ψ, Ψ is called the base function. University of Oxford Ralf Hinze

52 Generic Programming with Adjunctions Semantics of datatypes Two-level types Abstracting away from the recursive call. data Stack stack = Empty Push (Nat, stack) instance Functor Stack where fmap f (Empty) = Empty fmap f (Push (n, s)) = Push (n, f s) Tying the recursive knot. newtype µf = In {in : f (µf )} type Stack = µstack University of Oxford Ralf Hinze

53 Generic Programming with Adjunctions Semantics of datatypes Speaking categorically functor: Stack A = 1 + Nat A, a Stack-algebra: total : Stack Nat Nat total (Empty) = 0 total (Push (n, s)) = n + s total = zero plus, Stack-algebra: Nat, total. University of Oxford Ralf Hinze

54 Generic Programming with Adjunctions Semantics of datatypes The category of F-algebras Alg(F) let F : C C be an endofunctor, objects: A, a with A C and a C(F A, A), arrows: F-homomorphisms, h : A, a B, b if h C(A, B) such that h a = b F h, F A F A F h F B F B a A a A h b B b B identity: id A : A, a A, a, composition: in C. University of Oxford Ralf Hinze

55 Generic Programming with Adjunctions Semantics of datatypes The category of F-coalgebras Coalg(F) let F : C C be an endofunctor, objects: A, a with A C and a C(A, F A), arrows: F-homomorphisms, h : A, a B, b if h C(A, B) such that F h a = b h, A A h B B a F A a F A b F h F B b F B identity: id A : A, a A, a, composition: in C. University of Oxford Ralf Hinze

56 Generic Programming with Adjunctions Semantics of datatypes Fixed points of functors initial object in Alg(F): initial F-algebra µf, in, µf is the least fixed point of F, in : F (µf) µf, final object in Coalg(F): final F-coalgebra νf, out, νf is the greatest fixed point of F, out : νf F (νf). University of Oxford Ralf Hinze

57 Generic Programming with Adjunctions Semantics of datatypes Coq: inductive and coinductive types Inductive Nat : Type := Zero : Nat Succ : Nat Nat. Inductive Stack : Type := Empty : Stack Push : Nat Stack Stack. CoInductive Stream : Type := Cons : Nat Stream Stream. University of Oxford Ralf Hinze

58 Generic Programming with Adjunctions Mendler-style folds and unfolds Semantics of recursive functions total : µstack Nat total (In (Empty)) = 0 total (In (Push (n, s))) = n + total s University of Oxford Ralf Hinze

59 Generic Programming with Adjunctions Mendler-style folds and unfolds Abstracting away from the recursive call total : (µstack Nat) (µstack Nat) total total (In (Empty)) = 0 total total (In (Push (n, s))) = n + total s A function of this type has many fixed points. University of Oxford Ralf Hinze

60 Generic Programming with Adjunctions Mendler-style folds and unfolds removing in Abstracting away from the recursive call and removing in. total : x. (x Nat) (Stack x Nat) total total (Empty) = 0 total total (Push (n, s)) = n + total s A function of this type has a unique fixed point. Tying the recursive knot. total : µstack Nat total (In l) = total total l University of Oxford Ralf Hinze

61 Generic Programming with Adjunctions Mendler-style folds and unfolds Example: from data Sequ = Next (Nat, Sequ) from : Nat Sequ from n = Next (n, from (n + 1)) University of Oxford Ralf Hinze

62 Generic Programming with Adjunctions Mendler-style folds and unfolds Two-level types and functions data Sequ sequ = Next (Nat, sequ) from : x. (Nat x) (Nat Sequ x) from from n = Next (n, from (n + 1)) from : Nat νsequ from n = Out (from from n). University of Oxford Ralf Hinze

63 Generic Programming with Adjunctions Mendler-style folds and unfolds Initial fixed-point equations An initial fixed-point equation in the unknown x C(µF, A) has the syntactic form x in = Ψ x, where the base function Ψ has type Ψ : X. C(X, A) C(F X, A). The naturality of Ψ ensures termination. University of Oxford Ralf Hinze

64 Generic Programming with Adjunctions Mendler-style folds and unfolds Guarded by destructors x = Ψ x in x C(µF, A) Ψ : X. C(X, A) C(F X, A) µf in F (µf) Ψ x A University of Oxford Ralf Hinze

65 Generic Programming with Adjunctions Mendler-style folds and unfolds Mendler-style folds x = Ψ Id x in = Ψ x University of Oxford Ralf Hinze

66 Generic Programming with Adjunctions Mendler-style folds and unfolds Proof of uniqueness φ : C(F A, A) ( X. C(X, A) C(F X, A)) x in = Ψ x { isomorphism } x in = φ (φ Ψ) x { definition of φ : φ Ψ = Ψ id } x in = φ (Ψ id) x { definition of φ: φ f = λ κ. f F κ } x in = Ψ id F x { initial algebras } x = Ψ id University of Oxford Ralf Hinze

67 Generic Programming with Adjunctions Mendler-style folds and unfolds Final fixed-point equations A final fixed-point equation in the unknown x C(A, νf) has the syntactic form out x = Ψ x, where the base function Ψ has type Ψ : X. C(A, X ) C(A, F X ). The naturality of Ψ ensures productivity. University of Oxford Ralf Hinze

68 Generic Programming with Adjunctions Mendler-style folds and unfolds Guarded by constructors x = out Ψ x x C (A, νf) Ψ : X. C(A, X ) C(A, F X ) A Ψ x F (νf) out νf University of Oxford Ralf Hinze

69 Generic Programming with Adjunctions Mendler-style folds and unfolds Mendler-style unfolds x = [(Ψ)] Id out x = Ψ x University of Oxford Ralf Hinze

70 Generic Programming with Adjunctions Mendler-style folds and unfolds Mutual type recursion data Tree = Node Nat Trees data Trees = Nil Cons (Tree, Trees) flattena : Tree Stack flattena (Node n ts) = Push (n, flattens ts) flattens : Trees Stack flattens (Nil) = Empty flattens (Cons (t, ts)) = stack (flattena t, flattens ts) University of Oxford Ralf Hinze

71 Generic Programming with Adjunctions Mendler-style folds and unfolds Speaking categorically Idea: view Tree and Trees as a fixed point in a product category. T A, B = Nat B, 1 + A B flatten (C C)(µT, Stack, Stack ) University of Oxford Ralf Hinze

72 Generic Programming with Adjunctions Mendler-style folds and unfolds Specialising fixed-point equations An equation in C D corresponds to two equations, one in C and one in D. x in = Ψ x x 1 in 1 = Ψ 1 x 1, x 2 and x 2 in 2 = Ψ 2 x 1, x 2 Here, x 1 = Outl x, x 2 = Outr x, in 1 = Outl in, in 2 = Outr in, Ψ 1 = Outl Ψ and Ψ 2 = Outr Ψ. University of Oxford Ralf Hinze

73 Generic Programming with Adjunctions Mendler-style folds and unfolds Parametric datatypes data Perfect a = Zero a Succ (Perfect (a, a)) size : a. Perfect a Nat size (Zero a) = 1 size (Succ p) = 2 size p University of Oxford Ralf Hinze

74 Generic Programming with Adjunctions Mendler-style folds and unfolds Speaking categorically Idea: view Perfect as a fixed point in a functor category. P F = Λ A. A + F (A A) The second-order functor F sends a functor to a functor. size : µp K Nat NB K : D D C is the constant functor K A = Λ B. A. University of Oxford Ralf Hinze

75 Generic Programming with Adjunctions Mendler-style folds and unfolds Specialising fixed-point equations x in = Ψ x x A in A = Ψ x A NB Type application and abstraction are invisible in Haskell. University of Oxford Ralf Hinze

76 Generic Programming with Adjunctions Mendler-style folds and unfolds 3.2 initial fixed-point equation x in = Ψ x final fixed-point equation out x = Ψ x Set inductive type coinductive type standard fold standard unfold Cpo continuous coalgebra continuous unfold Cpo strict continuous fold strict continuous unfold continuous algebra continuous coalgebra (µf νf) C D mutually rec. ind. types mutually rec. coind. types mutually rec. folds mutually rec. unfolds D C inductive type functor coinductive type functor higher-order fold higher-order unfold University of Oxford Ralf Hinze

77 Generic Programming with Adjunctions Adjoint folds and unfolds Counterexample: stack stack : (µstack, Stack) Stack stack (In (Empty), bs) = bs stack (In (Push (a, as)), bs) = In (Push (a, stack (as, bs))) University of Oxford Ralf Hinze

78 Generic Programming with Adjunctions Adjoint folds and unfolds Counterexample: nats and squares nats : Nat νsequ nats n = Out (Next (n, squares n)) squares : Nat νsequ squares n = Out (Next (n n, nats (n + 1))) University of Oxford Ralf Hinze

79 Generic Programming with Adjunctions Adjoint folds and unfolds Adjoint fixed-point equations Idea: model the context by a functor. x L in = Ψ x R out x = Ψ x Requirement: the functors have to be adjoint: L R. University of Oxford Ralf Hinze

80 Generic Programming with Adjunctions Adjoint folds and unfolds Adjoint initial fixed-point equations An adjoint initial fixed-point equation in the unknown x C(L (µf), A) has the syntactic form x L in = Ψ x, where the base function Ψ has type Ψ : X : D. C(L X, A) C(L (F X ), A). The unique solution is called an adjoint fold. Furthermore, φ x is called the transposed fold. University of Oxford Ralf Hinze

81 Generic Programming with Adjunctions Adjoint folds and unfolds Proof of uniqueness x L in = Ψ x { adjunction } φ (x L in) = φ (Ψ x) { naturality of φ: φ f h = φ (f L h) } φ x in = φ (Ψ x) { adjunction } φ x in = (φ Ψ φ ) (φ x) { universal property of Mendler-style folds } φ x = φ Ψ φ Id { adjunction } x = φ φ Ψ φ Id University of Oxford Ralf Hinze

82 Generic Programming with Adjunctions Adjoint folds and unfolds Adjoint folds x = Ψ L x L in = Ψ x University of Oxford Ralf Hinze

83 Generic Programming with Adjunctions Adjoint folds and unfolds Banana-split law Φ L Ψ L = λ x. Φ (outl x) Ψ (outr x) L University of Oxford Ralf Hinze

84 Generic Programming with Adjunctions Adjoint folds and unfolds Proof of banana-split law ( Φ L Ψ L ) L in = { split-fusion } Φ L L in Ψ L L in = { fold-computation } Φ Φ L Ψ Ψ L = { split-computation } Φ (outl ( Φ L Ψ L )) Ψ (outl ( Φ L Ψ L )) University of Oxford Ralf Hinze

85 Generic Programming with Adjunctions Adjoint folds and unfolds Adjoint final fixed-point equations An adjoint final fixed-point equation in the unknown x D(A, R (νf)) has the syntactic form R out x = Ψ x, where the base function Ψ has type Ψ : X : C. D(A, R X ) D(A, R (F X )). The unique solution is called an adjoint unfold. University of Oxford Ralf Hinze

86 Generic Programming with Adjunctions Adjoint folds and unfolds Adjoint unfolds x = [(Ψ)] R R out x = Ψ x University of Oxford Ralf Hinze

87 Generic Programming with Adjunctions 4.0 Part 4 Adjunctions University of Oxford Ralf Hinze

88 Generic Programming with Adjunctions Outline 14. Identity 15. Currying 16. Mutual Value Recursion 17. Type Application 18. Type Composition University of Oxford Ralf Hinze

89 Generic Programming with Adjunctions Identity Recall: Adjoint fixed-point equations x L in = Ψ x R out x = Ψ x Requirement: the functors have to be adjoint: L R. University of Oxford Ralf Hinze

90 Generic Programming with Adjunctions Identity Identity C Id Id C φ : A B. C(Id A, B) C(A, Id B) Adjoint fixed-point equations subsume Mendler-style ones. University of Oxford Ralf Hinze

91 Generic Programming with Adjunctions Currying Recall: stack stack : (µstack, Stack) Stack stack (In (Empty), bs) = bs stack (In (Push (a, as)), bs) = In (Push (a, stack (as, bs))) The type µstack is embedded in a context L: L A = A Stack L f = f id Stack. University of Oxford Ralf Hinze

92 Generic Programming with Adjunctions Currying Currying C X ( ) X C φ : A B. C(A X, B) C(A, B X ) University of Oxford Ralf Hinze

93 Generic Programming with Adjunctions Currying Specialising adjoint equations x L in = Ψ x { definition of L } x (in id) = Ψ x { pointwise } x (in a, c) = Ψ x (a, c) R out x = Ψ x { definition of R } (out ) x = Ψ x { pointwise } out (x a c) = Ψ x a c University of Oxford Ralf Hinze

94 Generic Programming with Adjunctions Currying stack as an adjoint fold stack : x. (L x Stack) (L (Stack x) Stack) stack stack (Empty, bs) = bs stack stack (Push (a, as), bs) = In (Push (a, stack (as, bs))) stack : L (µstack) Stack stack (In as, bs) = stack stack (as, bs) University of Oxford Ralf Hinze

95 Generic Programming with Adjunctions Currying The transpose of stack R A = A Stack R f = f id Stack The transposed fold is the curried variant of stack. stack : µstack R Stack stack (In Empty) = λbs bs stack (In (Push (a, as))) = λbs In (Push (a, stack as bs)) University of Oxford Ralf Hinze

96 Generic Programming with Adjunctions Currying Recall: append append : a. (List a, List a) List a append (Nil, bs) = bs append (Cons (a, as), bs) = Cons (a, append (as, bs)) University of Oxford Ralf Hinze

97 Generic Programming with Adjunctions Currying Two-level types data LIST list a = Nil Cons (a, list a) instance (Functor list) Functor (LIST list) where fmap f (Nil) = Nil fmap f (Cons (a, as)) = Cons (f a, fmap f as) append : a. (µlist a, List a) List a append (In (Nil), bs) = bs append (In (Cons (a, as)), bs) = In (Cons (a, append (as, bs))) University of Oxford Ralf Hinze

98 Generic Programming with Adjunctions Currying append as a natural transformation Definining (F G) A = F A G A, we can view append as a natural transformation: append : List List List. We have to find the right adjoint of the lifted product H. University of Oxford Ralf Hinze

99 Generic Programming with Adjunctions Currying Deriving the right adjoint G H A { Yoneda lemma } C(A, ) G H { requirement: H H } C(A, ) H G { natural transformation } X : C. C(A, X ) H X G X { X X } X : C. C(A, X ) (G X ) H X. NB We assume that the functor category is Set C so G H : C Set. University of Oxford Ralf Hinze

100 Generic Programming with Adjunctions Currying The transpose of append append : List List List In Haskell: append : a. List a x. (a x) (List x List x) append as = λf λbs append (fmap f as, bs). NB append combines append with fmap. University of Oxford Ralf Hinze

101 Generic Programming with Adjunctions Mutual Value Recursion Recall: nats and squares nats : Nat νsequ nats n = Out (Next (n, squares n)) squares : Nat νsequ squares n = Out (Next (n n, nats (n + 1))) University of Oxford Ralf Hinze

102 Generic Programming with Adjunctions Mutual Value Recursion Speaking categorically numbers : Nat, Nat (νsequ) University of Oxford Ralf Hinze

103 Generic Programming with Adjunctions Mutual Value Recursion Adjoints of the diagonal functor φ : A B. C((+) A, B) (C C)(A, B) C + C C C φ : A B. (C C)( A, B) C(A, ( ) B) University of Oxford Ralf Hinze

104 Generic Programming with Adjunctions Mutual Value Recursion Specialising adjoint equations out x = Ψ x out x 1 = Ψ 1 x 1, x 2 and out x 2 = Ψ 2 x 1, x 2 Here, x 1 = Outl x, x 2 = Outr x, Ψ 1 = Outl Ψ and Ψ 2 = Outr Ψ. University of Oxford Ralf Hinze

105 Generic Programming with Adjunctions Mutual Value Recursion The transpose of nats and squares numbers : Either Nat Nat νsequ numbers (Left n) = Out (Next (n, numbers (Right n))) numbers (Right n) = Out (Next (n n, numbers (Left (n + 1)))) University of Oxford Ralf Hinze

106 Generic Programming with Adjunctions Mutual Value Recursion A special case: paramorphisms fac : µnat Nat fac (In (Z)) = 1 fac (In (S n)) = In (S (id n)) fac n id : µnat Nat id (In (Z)) = In Z id (In (S n)) = In (S (id n)) University of Oxford Ralf Hinze

107 Generic Programming with Adjunctions Mutual Value Recursion A special case: histomorphisms fib : µnat Nat fib (In (Z)) = 0 fib (In (S n)) = fib n fib : µnat Nat fib (In (Z)) = 1 fib (In (S n)) = fib n + fib n University of Oxford Ralf Hinze

108 Generic Programming with Adjunctions Type Application Recall: sum data List a = Nil Cons (a, List a) sum : List Nat Nat sum (Nil) = 0 sum (Cons (a, as)) = a + sum as University of Oxford Ralf Hinze

109 Generic Programming with Adjunctions Type Application Likewise for perfect trees sump : Perfect Nat Nat sump (Zero n) = n sump (Succ p) = sump (fmap plus p) plus (a, b) = a + b NB The recursive call is not applied to a subterm of Succ p. University of Oxford Ralf Hinze

110 Generic Programming with Adjunctions Type Application Speaking categorically where sum : App Nat List K Nat App X : C D C App X F = F X App X α = α X. University of Oxford Ralf Hinze

111 Generic Programming with Adjunctions Type Application 4.4 φ : A B. C D (Lsh X A, B) C(A, App X B) C D Lsh X App X C App X Rsh X CD φ : A B. C(App X A, B) C D (A, Rsh X B) University of Oxford Ralf Hinze

112 Generic Programming with Adjunctions Type Application Deriving the left adjoint C(A, App X B) { definition of App X } C(A, B X ) { Yoneda } Y : D. D(X, Y ) C(A, B Y ) { definition of a copower: Ix C(X, Y ) C( Ix. X, Y ) } Y : D. C( D(X, Y ). A, B Y ) { define Lsh X A = Λ Y : D. D(X, Y ). A } Y : D. C(Lsh X A Y, B Y ) { natural transformation } Lsh X A B University of Oxford Ralf Hinze

113 Generic Programming with Adjunctions Type Application Left shifts in Haskell newtype Lsh x a y = Lsh (x y, a) instance Functor (Lsh x a) where fmap f (Lsh (κ, a)) = Lsh (f κ, a) φ Lsh : ( y. Lsh x a y b y) (a b x) φ Lsh α = λs α (Lsh (id, s)) φ Lsh : (Functor b) (a b x) ( y. Lsh x a y b y) φ Lsh g = λ(lsh (κ, s)) fmap κ (g s) University of Oxford Ralf Hinze

114 Generic Programming with Adjunctions Type Application Right shifts in Haskell newtype Rsh x b y = Rsh {rsh : (y x) b} instance Functor (Rsh x b) where fmap f (Rsh g) = Rsh (λκ g (κ f )) φ Rsh : (Functor a) (a x b) ( y. a y Rsh x b y) φ Rsh f = λs Rsh (λκ f (fmap κ s)) φ Rsh : ( y. a y Rsh x b y) (a x b) φ Rsh β = λs rsh (β s) id University of Oxford Ralf Hinze

115 Generic Programming with Adjunctions Type Application Specialising adjoint equations x App X in = Ψ x { definition of App X } x in X = Ψ x University of Oxford Ralf Hinze

116 Generic Programming with Adjunctions Type Application The transpose of sump sump : x. Perfect x (x Nat) Nat sump (Zero n) = λκ κ n sump (Succ p) = λκ sump p (plus (κ κ)) University of Oxford Ralf Hinze

117 Generic Programming with Adjunctions Type Application Relation to Generic Haskell sump : x. (x Nat) (Perfect x Nat) sump sumx (Zero n) = sumx n sump sumx (Succ p) = sump (plus (sumx sumx)) p University of Oxford Ralf Hinze

118 Generic Programming with Adjunctions Type Composition Recall: concat concat : a. List (List a) List a concat (Nil) = Nil concat (Cons (l, ls)) = append (l, concat ls) University of Oxford Ralf Hinze

119 Generic Programming with Adjunctions Type Composition Speaking categorically where concat : Pre List (µlist) List Pre J : E D E C Pre J F = F J Pre J α = α J. University of Oxford Ralf Hinze

120 Generic Programming with Adjunctions Type Composition 4.5 φ : F G. E D (Lan J F, G) E C (F, G J) C C E G LanJ F F J D E D Lan J ( J) ( J) EC Ran J ED J D G F Ran J G E φ : F G. E C (F J, G) E D (F, Ran J G) University of Oxford Ralf Hinze

121 Generic Programming with Adjunctions Type Composition 4.5 F J G { natural transformation as an end } A : C. E(F (J A), G A) { Yoneda } A : C. X : D. D(X, J A) E(F X, G A) { definition of power: Ix C(A, B) C(A, Ix. B) } A : C. X : D. E(F X, D(X, J A). G A) { interchange of quantifiers } X : D. A : C. E(F X, D(X, J A). G A) { the functor E(F X, ) preserves ends } X : D. E(F X, A : C. D(X, J A). G A) { define Ran J G = Λ X : D. A : C. D(X, J A). G A } X : D. E(F X, Ran J G X ) { natural transformation as an end } F Ran J G University of Oxford Ralf Hinze

122 Generic Programming with Adjunctions Type Composition Right Kan extensions in Haskell newtype Ran i g x = Ran {ran : a. (x i a) g a} instance Functor (Ran i g) where fmap f (Ran h) = Ran (λκ h (κ f )) φ Ran : (Functor f ) ( x. f (i x) g x) ( x. f x Ran i g x) φ Ran α = λs Ran (λκ α (fmap κ s)) φ Ran : ( x. f x Ran i g x) ( x. f (i x) g x) φ Ran β = λs ran (β s) id University of Oxford Ralf Hinze

123 Generic Programming with Adjunctions Type Composition Left Kan extensions in Haskell data Lan i f x = a. Lan (i a x, f a) instance Functor (Lan i f ) where fmap f (Lan (κ, s)) = Lan (f κ, s) φ Lan : ( x. Lan i f x g x) ( x. f x g (i x)) φ Lan α = λs α (Lan (id, s)) φ Lan : (Functor g) ( x. f x g (i x)) ( x. Lan i f x g x) φ Lan β = λ(lan (κ, s)) fmap κ (β s) University of Oxford Ralf Hinze

124 Generic Programming with Adjunctions Type Composition The transpose of concat concat : a b. µlist a (a List b) List b concat as = λκ concat (fmap κ as) The transpose of concat is the bind of the list monad (written >= in Haskell)! University of Oxford Ralf Hinze

125 Generic Programming with Adjunctions Type Composition 4.5 adjunction initial fixed-point equation final fixed-point equation x L in = Ψ x R out x = Ψ x L R φ x in = (φ Ψ φ ) (φ x) out φ x = (φ Ψ φ) (φ x) Id Id ( X ) ( X ) (+) ( ) standard fold standard fold parametrised fold fold to an exponential recursion from a coproduct of mutually recursive types mutual value recursion on mutually recursive types mutual value recursion single recursion to a product domain Lsh X ( X ) monomorphic fold ( X ) Rsh X fold to a right shift Lan J ( J) polymorphic fold ( J) Ran J fold to a right Kan extension standard unfold standard unfold curried unfold unfold from a pair mutual value recursion single recursion from a coproduct domain recursion to a product of mutually recursive types mutual value recursion on mutually recursive types monomorphic unfold unfold from a left shift polymorphic unfold unfold from a left Kan extension University of Oxford Ralf Hinze

126 Generic Programming with Adjunctions 5.0 Part 5 Application: Type fusion University of Oxford Ralf Hinze

127 Generic Programming with Adjunctions Outline 19. Memoisation 20. Fusion 21. Type fusion 22. Application: firstification 23. Application: type specialisation 24. Application: tabulation University of Oxford Ralf Hinze

128 Generic Programming with Adjunctions Memoisation Memoisation Say, you want to memoise the function f : Nat V so that it caches previously computed values. University of Oxford Ralf Hinze

129 Generic Programming with Adjunctions Memoisation 5.1 Given the interface data Table v lookup : v. Table v (Nat v) tabulate : v. (Nat v) Table v, we can memoize f as follows memo-f : Nat V memo-f = lookup (tabulate f ). University of Oxford Ralf Hinze

130 Generic Programming with Adjunctions Memoisation Implementing Table data Nat = Zero Succ Nat data Table v = Node {zero : v, succ : Table v } lookup (Node {zero = t }) Zero = t lookup (Node {succ = t }) (Succ n) = lookup t n tabulate f = Node {zero = f Zero, succ = tabulate (λn f (Succ n))} University of Oxford Ralf Hinze

131 Generic Programming with Adjunctions Fusion Fusion for adjoint folds Let α : X D. C(L X, B) C (L X, B ), then α Ψ L = Ψ L = α Ψ = Ψ α. NB This subsumes the fusion law for folds. University of Oxford Ralf Hinze

132 Generic Programming with Adjunctions Fusion Proof of fusion α Ψ L L in = { naturality of α: α x L h = α (x L h) } α ( Ψ L L in) = { computation } α (Ψ Ψ L ) = { assumption α Ψ = Ψ α } Ψ (α Ψ L ) University of Oxford Ralf Hinze

133 Generic Programming with Adjunctions Type fusion Type fusion C G G C L R D F F D L (µf) µg = L F G L νf R (νg) = F R R G University of Oxford Ralf Hinze

134 Generic Programming with Adjunctions Type fusion 5.3 τ : L (µf) µg = swap : L F G L University of Oxford Ralf Hinze

135 Generic Programming with Adjunctions Type fusion Definition of τ and τ L (F (µf)) swap swap G (L (µf)) G τ G τ G (µg) L in L in L (µf) τ τ in in µg τ L in = in G τ swap and τ in = L in swap G τ University of Oxford Ralf Hinze

136 Generic Programming with Adjunctions Type fusion Proof of τ τ = id µg (τ τ ) in = { definition of τ } τ L in swap G τ = { definition of τ } in G τ swap swap G τ = { inverses } in G τ G τ = { G functor } in G (τ τ ) The equation x in = in G x has a unique solution. Since id is also a solution, the result follows. University of Oxford Ralf Hinze

137 Generic Programming with Adjunctions Type fusion Proof of τ τ = id L (µf) (τ τ) L in = { definition of τ } τ in G τ swap = { definition of τ } L in swap G τ G τ swap = { G functor } L in swap G (τ τ) swap Again, x L in = L in swap G x swap has a unique solution. And again, id is also solution, which implies the result. University of Oxford Ralf Hinze

138 Generic Programming with Adjunctions Application: firstification Application: firstification data Stack = Empty Push (Nat, Stack) data List a = Nil Cons (a, List a) List Nat Stack University of Oxford Ralf Hinze

139 Generic Programming with Adjunctions Application: firstification Speaking categorically = App Nat (µlist) µstack App Nat LIST Stack App Nat University of Oxford Ralf Hinze

140 Generic Programming with Adjunctions Application: firstification Proof of App Nat LIST Stack App Nat App Nat LIST { composition of functors and definition of App } Λ X. LIST X Nat { definition of LIST } Λ X. 1 + Nat X Nat { definition of Stack } Λ X. Stack (X Nat) { composition of functors and definition of App } Stack App Nat University of Oxford Ralf Hinze

141 Generic Programming with Adjunctions Application: firstification In Haskell swap : x. LIST x Nat Stack (x Nat) swap Nil = Empty swap (Cons (n, x)) = Push (n, x) swap : x. Stack (x Nat) LIST x Nat swap Empty = Nil swap (Push (n, x)) = Cons (n, x) Λ-lift : µstack µlist Nat Λ-lift (In x) = In (swap (fmap Λ-lift x)) Λ-drop : µlist Nat µstack Λ-drop (In x) = In (fmap Λ-drop (swap x)) University of Oxford Ralf Hinze

142 Generic Programming with Adjunctions Application: type specialisation Application: type specialisation Lists of optional values, List Maybe with data Maybe a = Nothing Just a, can be represented more compactly using the tailor-made data Sequ a = Done Skip (Sequ a) Yield (a, Sequ a). University of Oxford Ralf Hinze

143 Generic Programming with Adjunctions Application: type specialisation Speaking categorically List Maybe Sequ, = Pre Maybe (µlist) µsequ Pre Maybe LIST SEQU Pre Maybe University of Oxford Ralf Hinze

144 Generic Programming with Adjunctions Application: type specialisation Proof of Pre Maybe LIST SEQU Pre Maybe LIST X Maybe { composition of functors } Λ A. LIST X (Maybe A) { definition of LIST } Λ A. 1 + Maybe A X (Maybe A) { definition of Maybe } Λ A. 1 + (1 + A) X (Maybe A) { distributes over + and 1 B B } Λ A. 1 + X (Maybe A) + A X (Maybe A) { composition of functors } Λ A. 1 + (X Maybe) A + A (X Maybe) A { definition of SEQU } SEQU (X Maybe) University of Oxford Ralf Hinze

145 Generic Programming with Adjunctions Application: type specialisation In Haskell swap : x. a. LIST x (Maybe a) SEQU (x Maybe) a swap (Nil) = Done swap (Cons (Nothing, x)) = Skip x swap (Cons (Just a, x)) = Yield (a, x) University of Oxford Ralf Hinze

146 Generic Programming with Adjunctions Application: tabulation Recall Nat and Table data Nat = Zero Succ Nat data Table val = Node {zero : val, succ : Table val } V Nat Table V University of Oxford Ralf Hinze

147 Generic Programming with Adjunctions Application: tabulation 5.6 ( ) Nat Table University of Oxford Ralf Hinze

148 Generic Programming with Adjunctions Application: tabulation Truth tables ( ) : Bool Bool Bool False False False True University of Oxford Ralf Hinze

149 Generic Programming with Adjunctions Application: tabulation 5.6 ( ) Bool Bool (Id Id) (Id Id) University of Oxford Ralf Hinze

150 Generic Programming with Adjunctions Application: tabulation Laws of exponentials V 0 1 V 1 V V A+B V A V B V A B (V B ) A University of Oxford Ralf Hinze

151 Generic Programming with Adjunctions Application: tabulation Curried exponentiation Exp : C (C C ) op Exp K = Λ V. V K Exp f = Λ V. (id V ) f University of Oxford Ralf Hinze

152 Generic Programming with Adjunctions Application: tabulation Laws of exponentials Exp 0 K 1 Exp 1 Id Exp (A + B) Exp A Exp B Exp (A B) Exp A Exp B University of Oxford Ralf Hinze

153 Generic Programming with Adjunctions Application: tabulation Exp is a left adjoint (C C ) op G Exp G (CC op ) Sel C F F C University of Oxford Ralf Hinze

154 Generic Programming with Adjunctions Application: tabulation Deriving the right adjoint (C C ) op (Exp A, B) { definition of op } C C (B, Exp A) { natural transformation as an end } X C. C(B X, Exp A X ) { definition of Exp } X C. C(B X, X A ) { Y ( ) Y and Y Z Z Y } X C. C(A, X B X ) { the functor C(A, ) preserves ends } C(A, X C. X B X ) { define Sel B = X C. X B X } C(A, Sel B) University of Oxford Ralf Hinze

155 Generic Programming with Adjunctions Application: tabulation 5.6 (C C ) op G Exp G (CC op ) Sel C F F C Since Exp is a contra-variant functor, τ and swap live in an opposite category. Type fusion in terms of arrows in C C : τ : νg Exp (µf) = swap : G Exp Exp F. University of Oxford Ralf Hinze

156 Generic Programming with Adjunctions Application: tabulation Look-up and tabulate The isomorphism τ : νg Exp (µf) is a curried look-up function that maps a memo table to an exponential. lookup (Out t) (in i) = swap (G lookup t) i The inverse τ : Exp (µf) νg is a transformation that tabulates a given exponential. tabulate f = Out (G tabulate (swap (f in))) University of Oxford Ralf Hinze

157 Generic Programming with Adjunctions Application: tabulation In Haskell The transformation swap implements V V X V 1+X. swap : x. val. TABLE (Exp x) val (Nat x val) swap (Node (v, t)) (Zero) = v swap (Node (v, t)) (Succ n) = t n The inverse of swap implements V 1+X V V X. swap : x. val. (Nat x val) TABLE (Exp x) val swap f = Node (f Zero, f Succ) University of Oxford Ralf Hinze

158 Generic Programming with Adjunctions Application: tabulation In Haskell lookup : val. νtable val (µnat val) lookup (Out (Node (v, t))) (In Zero) = v lookup (Out (Node (v, t))) (In (Succ n)) = lookup t n tabulate : val. (µnat val) νtable val tabulate f = Out (Node (f (In Zero), tabulate (f In Succ))) University of Oxford Ralf Hinze

159 Generic Programming with Adjunctions 6.0 Part 6 Epilogue University of Oxford Ralf Hinze

160 Generic Programming with Adjunctions Summary Adjoint (un-) folds capture many recursion schemes. Adjunctions play a central role. Tabulation is an intriguing example. University of Oxford Ralf Hinze

161 Generic Programming with Adjunctions Limitations Simultaneous recursion doesn t fit under the umbrella. zip : (List a, List b) List (a, b) zip (Nil, bs) = Nil zip (as, Nil) = Nil zip (Cons (a, as), Cons (b, bs)) = Cons ((a, b), zip (as, bs)) However, one can establish x = Ψ x ( ) in = Ψ x using a different technique (colimits). See, R. Bird, R. Paterson: Generalised folds for nested datatypes. University of Oxford Ralf Hinze

162 Generic Programming with Adjunctions 7.0 Part 7 Tagless interpreters University of Oxford Ralf Hinze

163 Generic Programming with Adjunctions Initial algebras: view from the left data Expr 0 = Lit Nat Add (Expr 0, Expr 0 ) e 0 : Expr 0 e 0 = Add (Lit 4700, Lit 11) University of Oxford Ralf Hinze

164 Generic Programming with Adjunctions 7.0 data Expr expr = Lit Nat Add (expr, expr) The evaluation algebra. eval 0 : Expr Nat Nat eval 0 (Lit n) = n eval 0 (Add (n 1, n 2 )) = n 1 + n 2 The fold for expressions. fold 0 : val. (Expr val val) (Expr 0 val) fold 0 alg (Lit n) = alg (Lit n) fold 0 alg (Add (e 1, e 2 )) = alg (Add (fold 0 alg e 1, fold 0 alg e 2 )) University of Oxford Ralf Hinze

165 Generic Programming with Adjunctions 7.0 C(Expr Val, Val) { definition of Expr } C(Nat + (Val Val), Val) { (+) } (C C)( Nat, Val Val, Val) { product categories } C(Nat, Val) C(Val Val, Val) data Alg val = Alg {lit : Nat val, add : (val, val) val } University of Oxford Ralf Hinze

166 Generic Programming with Adjunctions 7.0 data Alg val = Alg {lit : Nat val, add : (val, val) val } The evaluation algebra. eval 0 : Alg Nat eval 0 = Alg {lit = id, add = λ(n 1, n 2 ) n 1 + n 2 } The fold for expressions. fold 0 : val. Alg val (Expr 0 val) fold 0 alg (Lit n) = lit alg n fold 0 alg (Add (e 1, e 2 )) = add alg (fold 0 alg e 1, fold 0 alg e 2 ) University of Oxford Ralf Hinze

167 Generic Programming with Adjunctions Initial algebras: view from the right val. Alg val (Expr 0 val) { A (B C) B (A C) } val. Expr 0 (Alg val val) { a. A T a A a. T a } Expr 0 ( val. Alg val val) University of Oxford Ralf Hinze

168 Generic Programming with Adjunctions using records newtype Expr 1 = Expr {fold 1 : val. Alg val val } e 1 : Expr 1 e 1 = Expr {fold 1 = λalg add alg (lit alg 4700, lit alg 11)} Converting between the left and right view. toright : Expr 0 Expr 1 toright e = Expr {fold 1 = λi fold 0 i e} toleft : Expr 1 Expr 0 toleft e = fold 1 e (Alg {lit = Lit, add = Add }) University of Oxford Ralf Hinze

169 Generic Programming with Adjunctions using classes class Alg val where {lit : Nat val; add : (val, val) val } e 1 : (Alg val) val e 1 = add (lit 4700, lit 11) Converting between the left and right view. toright : (Alg val) Expr 0 val toright e = fold 0 (Alg {lit = lit, add = add }) e instance Alg Expr 0 where {lit = Lit; add = Add } toleft : Expr 0 Expr 0 toleft e = e University of Oxford Ralf Hinze

170 Generic Programming with Adjunctions Parametricity A. (F A A) A (φ, φ) A. (F A A) A { polymorphic type } h. (φ A 1, φ A 2 ) (F h h) h { function type } h. f 1 f 2. (f 1, f 2 ) F h h = (φ A 1 f 1, φ A 2 f 2 ) h { base } h. f 1 f 2. (f 1, f 2 ) F h h = h (φ A 1 f 1 ) = φ A 2 f 2 { function type } h. f 1 f 2. h f 1 = f 2 F h = h (φ A 1 f 1 ) = φ A 2 f 2 University of Oxford Ralf Hinze

171 Generic Programming with Adjunctions An isomorphism toright i = λ a. a i toleft f = f in toleft (toright i) = { definition of toright } toleft (λ a. a i) = { definition of toleft } in i = { reflection } i University of Oxford Ralf Hinze

172 Generic Programming with Adjunctions 7.0 toright i = λ a. a i toleft f = f in toright (toleft f ) = { definition of toleft } toright (f in) = { definition of toright } λ a. a (f in) = { parametricity with a in = a F a } λ a. f a = { extensionality } f University of Oxford Ralf Hinze

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

Topos Theory. Lectures 3-4: Categorical preliminaries II. Olivia Caramello. Topos Theory. Olivia Caramello. Basic categorical constructions

Topos Theory. Lectures 3-4: Categorical preliminaries II. Olivia Caramello. Topos Theory. Olivia Caramello. Basic categorical constructions Lectures 3-4: Categorical preliminaries II 2 / 17 Functor categories Definition Let C and D be two categories. The functor category [C,D] is the category having as objects the functors C D and as arrows

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

Generalized Iteration and Coiteration for Higher-Order Nested Datatypes

Generalized Iteration and Coiteration for Higher-Order Nested Datatypes Generalized Iteration and Coiteration for Higher-Order Nested Datatypes Mendler rules! Andreas Abel (joint work with Ralph Matthes and Tarmo Uustalu) Slide 1 FoSSaCS 2003 Warsaw, Poland April 8, 2003 Work

More information

Natural Numbers. We will use natural numbers to illustrate several ideas that will apply to Haskell data types in general.

Natural Numbers. We will use natural numbers to illustrate several ideas that will apply to Haskell data types in general. Natural Numbers We will use natural numbers to illustrate several ideas that will apply to Haskell data types in general. For the moment we will ignore that fact that each type in Haskell includes possible

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

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

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

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

Haskell does it with class: Functorial unparsing

Haskell does it with class: Functorial unparsing Under consideration for publication in J. Functional Programming 1 F U N C T I O N A L P E A R L Haskell does it with class: Functorial unparsing RALF HINZE Institute of Information and Computing Sciences,

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

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

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages Harvard School of Engineering and Applied Sciences CS 152: Programming Languages Lecture 18 Thursday, March 29, 2018 In abstract algebra, algebraic structures are defined by a set of elements and operations

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

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

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

Inductive datatypes in HOL. lessons learned in Formal-Logic Engineering

Inductive datatypes in HOL. lessons learned in Formal-Logic Engineering Inductive datatypes in HOL lessons learned in Formal-Logic Engineering Stefan Berghofer and Markus Wenzel Institut für Informatik TU München = Isabelle λ β HOL α 1 Introduction Applications of inductive

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

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

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

An Algebra of Dependent Data Types

An Algebra of Dependent Data Types An Algebra of Dependent Data Types TYPES 2006 Tyng-Ruey Chuang Joint work with Jan-Li Lin Institute of Information Science, Academia Sinica Nangang, Taipei 115, Taiwan trc@iis.sinica.edu.tw 1 List in Coq

More information

Categorical models of type theory

Categorical models of type theory 1 / 59 Categorical models of type theory Michael Shulman February 28, 2012 2 / 59 Outline 1 Type theory and category theory 2 Categorical type constructors 3 Dependent types and display maps 4 Fibrations

More information

Generic Programming With Dependent Types: II

Generic Programming With Dependent Types: II Generic Programming With Dependent Types: II Generic Haskell in Agda Stephanie Weirich University of Pennsylvania March 2426, 2010 SSGIP Generic-Haskell style generic programming in Agda Dependently-typed

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

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

The three faces of homotopy type theory. Type theory and category theory. Minicourse plan. Typing judgments. Michael Shulman.

The three faces of homotopy type theory. Type theory and category theory. Minicourse plan. Typing judgments. Michael Shulman. The three faces of homotopy type theory Type theory and category theory Michael Shulman 1 A programming language. 2 A foundation for mathematics based on homotopy theory. 3 A calculus for (, 1)-category

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

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

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

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

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

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

THE DOLD-KAN CORRESPONDENCE

THE DOLD-KAN CORRESPONDENCE THE DOLD-KAN CORRESPONDENCE 1. Simplicial sets We shall now introduce the notion of a simplicial set, which will be a presheaf on a suitable category. It turns out that simplicial sets provide a (purely

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

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

MPRI course 2-4 Functional programming languages Exercises

MPRI course 2-4 Functional programming languages Exercises MPRI course 2-4 Functional programming languages Exercises Xavier Leroy October 13, 2016 Part I: Interpreters and operational semantics Exercise I.1 (**) Prove theorem 2 (the unique decomposition theorem).

More information

FUNCTIONAL PEARL Typed quote/antiquote or: Compile-time parsing

FUNCTIONAL PEARL Typed quote/antiquote or: Compile-time parsing JFP 21 (3): 219 234, 2011. c Cambridge University Press 2011 doi:10.1017/s0956796811000050 219 FUNCTIONAL PEARL Typed quote/antiquote or: Compile-time parsing RALF HINZE Department of Computer Science,

More information

Leinster s globular theory of weak -categories

Leinster s globular theory of weak -categories Leinster s globular theory of weak -categories Ed Morehouse April 16, 2014 (last updated August 8, 2014) These are my notes for a series of lectures that I gave at the Homotopy Type Theory seminar at Carnegie

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

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

Programming with Dependent Types Interactive programs and Coalgebras

Programming with Dependent Types Interactive programs and Coalgebras Programming with Dependent Types Interactive programs and Coalgebras Anton Setzer Swansea University, Swansea, UK 14 August 2012 1/ 50 A Brief Introduction into ML Type Theory Interactive Programs in Dependent

More information

Program Calculus Calculational Programming

Program Calculus Calculational Programming Program Calculus Calculational Programming National Institute of Informatics June 21 / June 28 / July 5, 2010 Program Calculus Calculational Programming What we will learn? Discussing the mathematical

More information

The language of categories

The language of categories The language of categories Mariusz Wodzicki March 15, 2011 1 Universal constructions 1.1 Initial and inal objects 1.1.1 Initial objects An object i of a category C is said to be initial if for any object

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

Mathematics for Computer Scientists 2 (G52MC2)

Mathematics for Computer Scientists 2 (G52MC2) Mathematics for Computer Scientists 2 (G52MC2) L07 : Operations on sets School of Computer Science University of Nottingham October 29, 2009 Enumerations We construct finite sets by enumerating a list

More information

The essence of dataflow programming. Teooriapäevad Kokel 2,

The essence of dataflow programming. Teooriapäevad Kokel 2, The essence of dataflow programming Tarmo UUSTALU Varmo VENE Teooriapäevad Kokel 2, 4.-6.2.2005 Motivation Following Moggi and Wadler, it is standard in programming and semantics to analyze various notions

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

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

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

CS611 Lecture 33 Equirecursive types & Recursive domain equations November 19, 2001

CS611 Lecture 33 Equirecursive types & Recursive domain equations November 19, 2001 CS611 Lecture 33 Equirecursive types & Recursive domain equations November 19, 001 Scribe: Hongzhou Liu and Junhwan Kim Lecturer: Andrew Myers 1 Semantics of recursive types, part There are two basic approaches

More information

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, hi, 3.2), c 4, a 1, b 5} 9/10/2017 4 Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Sasa Misailovic 4110 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421a # true;; - : bool = true # false;; - : bool

More information

CSE-321 Programming Languages 2012 Midterm

CSE-321 Programming Languages 2012 Midterm Name: Hemos ID: CSE-321 Programming Languages 2012 Midterm Prob 1 Prob 2 Prob 3 Prob 4 Prob 5 Prob 6 Total Score Max 14 15 29 20 7 15 100 There are six problems on 24 pages in this exam. The maximum score

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

Lecture Notes on Data Representation

Lecture Notes on Data Representation Lecture Notes on Data Representation 15-814: Types and Programming Languages Frank Pfenning Lecture 9 Tuesday, October 2, 2018 1 Introduction In this lecture we ll see our type system in action. In particular

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

The Worker/Wrapper Transformation

The Worker/Wrapper Transformation The Worker/Wrapper Transformation Andy Gill 1 Graham Hutton 2 1 The University of Kansas 2 The University of Nottingham March 26th, 2009 Andy Gill, Graham Hutton The Worker/Wrapper Transformation March

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

Basic Foundations of Isabelle/HOL

Basic Foundations of Isabelle/HOL Basic Foundations of Isabelle/HOL Peter Wullinger May 16th 2007 1 / 29 1 Introduction into Isabelle s HOL Why Type Theory Basic Type Syntax 2 More HOL Typed λ Calculus HOL Rules 3 Example proof 2 / 29

More information

Nested Datatypes. Wolfson Building, Parks Road, Oxford, OX1 3QD, UK.

Nested Datatypes. Wolfson Building, Parks Road, Oxford, OX1 3QD, UK. Nested Datatypes Richard Bird 1 and Lambert Meertens 2 1 Programming Research Group, Oxford University Wolfson Building, Parks Road, Oxford, OX1 3QD, UK bird@comlab.ox.ac.uk 2 CWI and Department of Computer

More information

The formal theory of homotopy coherent monads

The formal theory of homotopy coherent monads The formal theory of homotopy coherent monads Emily Riehl Harvard University http://www.math.harvard.edu/~eriehl 23 July, 2013 Samuel Eilenberg Centenary Conference Warsaw, Poland Joint with Dominic Verity.

More information

Refining Inductive Types

Refining Inductive Types Archived version from NCDOCKS Institutional Repository http://libres.uncg.edu/ir/asu/ Refining Inductive Types By: Atkey, Robert; Johann, Patricia; Ghani, Neil Abstract Dependently typed programming languages

More information

CIS 500 Software Foundations Midterm I

CIS 500 Software Foundations Midterm I CIS 500 Software Foundations Midterm I October 11, 2006 Name: Student ID: Email: Status: Section: registered for the course not registered: sitting in to improve a previous grade not registered: just taking

More information

Idioms are oblivious, arrows are meticulous, monads are promiscuous

Idioms are oblivious, arrows are meticulous, monads are promiscuous MSFP 2008 Idioms are oblivious, arrows are meticulous, monads are promiscuous Sam Lindley, Philip Wadler and Jeremy Yallop Laboratory for Foundations of Computer Science The University of Edinburgh Abstract

More information

Disciplined, efficient, generalised folds for nested datatypes

Disciplined, efficient, generalised folds for nested datatypes Under consideration for publication in Formal Aspects of Computing Disciplined, efficient, generalised folds for nested datatypes Clare Martin 1, Jeremy Gibbons 2 and Ian Bayley 2 1 School of Computing

More information

Recursively defined cpo algebras

Recursively defined cpo algebras Recursively defined cpo algebras Ohad Kammar and Paul Blain Levy July 13, 2018 Ohad Kammar and Paul Blain Levy Recursively defined cpo algebras July 13, 2018 1 / 16 Outline 1 Bilimit compact categories

More information

A Pronominal Account of Binding and Computation

A Pronominal Account of Binding and Computation A Pronominal Account of Binding and Computation Robert Harper Carnegie Mellon University TAASN March 2009 Thanks Thanks to Daniel R. Licata and Noam Zeilberger, my collaborators on this work. Thanks to

More information

Pattern Matching and Abstract Data Types

Pattern Matching and Abstract Data Types Pattern Matching and Abstract Data Types Tom Murphy VII 3 Dec 2002 0-0 Outline Problem Setup Views ( Views: A Way For Pattern Matching To Cohabit With Data Abstraction, Wadler, 1986) Active Patterns (

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

Monads T T T T T. Dually (by inverting the arrows in the given definition) one can define the notion of a comonad. T T

Monads T T T T T. Dually (by inverting the arrows in the given definition) one can define the notion of a comonad. T T Monads Definition A monad T is a category C is a monoid in the category of endofunctors C C. More explicitly, a monad in C is a triple T, η, µ, where T : C C is a functor and η : I C T, µ : T T T are natural

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

CSE-321 Programming Languages 2011 Final

CSE-321 Programming Languages 2011 Final Name: Hemos ID: CSE-321 Programming Languages 2011 Final Prob 1 Prob 2 Prob 3 Prob 4 Prob 5 Prob 6 Total Score Max 15 15 10 17 18 25 100 There are six problems on 18 pages in this exam, including one extracredit

More information

Types and Programming Languages. Lecture 8. Recursive type

Types and Programming Languages. Lecture 8. Recursive type Types and Programming Languages Lecture 8. Recursive type Xiaojuan Cai cxj@sjtu.edu.cn BASICS Lab, Shanghai Jiao Tong University Fall, 2016 List[T] List[T] is a type constructor whose elements are lists

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

Foundational Nonuniform (Co)datatypes for Higher-Order Logic

Foundational Nonuniform (Co)datatypes for Higher-Order Logic Foundational Nonuniform (Co)datatypes for Higher-Order Logic Jasmin Christian Blanchette, Fabian Meier, Andrei Popescu, and Dmitriy Traytel Vrije Universiteit Amsterdam, The Netherlands, and Inria & LORIA,

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

Type Systems Winter Semester 2006

Type Systems Winter Semester 2006 Type Systems Winter Semester 2006 Week 4 November 8 November 15, 2006 - version 1.1 The Lambda Calculus The lambda-calculus If our previous language of arithmetic expressions was the simplest nontrivial

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

Accurate Step Counting

Accurate Step Counting Accurate Step Counting Catherine Hope and Graham Hutton University of Nottingham Abstract Starting with an evaluator for a language, an abstract machine for the same language can be mechanically derived

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

Parametricity and Dependent Types

Parametricity and Dependent Types Parametricity and Dependent Types Jean-Philippe Bernardy Patrik Jansson Chalmers University of Technology and University of Gothenburg {bernardy,patrikj}@chalmers.se Ross Paterson City University London

More information

The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 4 MODULE, SPRING SEMESTER MATHEMATICAL FOUNDATIONS OF PROGRAMMING ANSWERS

The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 4 MODULE, SPRING SEMESTER MATHEMATICAL FOUNDATIONS OF PROGRAMMING ANSWERS The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 4 MODULE, SPRING SEMESTER 2012 2013 MATHEMATICAL FOUNDATIONS OF PROGRAMMING ANSWERS Time allowed TWO hours Candidates may complete the front

More information

From Types to Sets in Isabelle/HOL

From Types to Sets in Isabelle/HOL From Types to Sets in Isabelle/HOL Extented Abstract Ondřej Kunčar 1 and Andrei Popescu 1,2 1 Fakultät für Informatik, Technische Universität München, Germany 2 Institute of Mathematics Simion Stoilow

More information

Metrics on diagrams and persistent homology

Metrics on diagrams and persistent homology Background Categorical ph Relative ph More structure Department of Mathematics Cleveland State University p.bubenik@csuohio.edu http://academic.csuohio.edu/bubenik_p/ July 18, 2013 joint work with Vin

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

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

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

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

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 03: Bare-Bones Haskell Continued: o Function Application = Rewriting by Pattern Matching o Haskell

More information

CSE-321 Programming Languages 2010 Midterm

CSE-321 Programming Languages 2010 Midterm Name: Hemos ID: CSE-321 Programming Languages 2010 Midterm Score Prob 1 Prob 2 Prob 3 Prob 4 Total Max 15 30 35 20 100 1 1 SML Programming [15 pts] Question 1. [5 pts] Give a tail recursive implementation

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

CIS 500 Software Foundations Fall September 25

CIS 500 Software Foundations Fall September 25 CIS 500 Software Foundations Fall 2006 September 25 The Lambda Calculus The lambda-calculus If our previous language of arithmetic expressions was the simplest nontrivial programming language, then the

More information

Generic Programming in 3D

Generic Programming in 3D Generic Programming in 3D Ralf Hinze a, Andres Löh b a Institut für Informatik III, Universität Bonn Römerstraße 164, 53117 Bonn, Germany b Utrecht University, Department of Information and Computing Sciences

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

Compositional Soundness Proofs of Abstract Interpreters

Compositional Soundness Proofs of Abstract Interpreters Compositional Soundness Proofs of Abstract Interpreters SVEN KEIDEL, CASPER BACH POULSEN, and SEBASTIAN ERDWEG, Delft University of Technology, The Netherlands Abstract interpretation is a technique for

More information

Contractive Signatures with Recursive Types, Type Parameters, and Abstract Types

Contractive Signatures with Recursive Types, Type Parameters, and Abstract Types Contractive Signatures with Recursive Types, Type Parameters, and Abstract Types Hyeonseung Im 1, Keiko Nakata 2, and Sungwoo Park 3 1 LRI - Université Paris-Sud 11, Orsay, France 2 Institute of Cybernetics

More information

Probabilistic systems a place where categories meet probability

Probabilistic systems a place where categories meet probability Probabilistic systems a place where categories meet probability Ana Sokolova SOS group, Radboud University Nijmegen University Dortmund, CS Kolloquium, 12.6.6 p.1/32 Outline Introduction - probabilistic

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

Value Recursion in Monadic Computations

Value Recursion in Monadic Computations Value Recursion in Monadic Computations Levent Erkök OGI School of Science and Engineering, OHSU Advisor: John Launchbury June 24th, 2002 Outline Recursion and effects Motivating examples Value recursion

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