Polymorphic Contexts FP-Dag 2015

Size: px
Start display at page:

Download "Polymorphic Contexts FP-Dag 2015"

Transcription

1 Polymorphic Contexts FP-Dag 2015 Doaitse Swierstra January 14, 2015

2 Goal of this Talk To show you: that lazy evaluation requires a type system which extend beyond system-f how the Utrecht Haskell Compiler can handle such extensions how to achieve the desired effects in GHC anyway 2

3 Message to take home In languages with lazy evaluation: A function takes arguments and returns results A context takes results and provides arguments 3

4 The repmin problem The repmin program computes, given a tree, a tree of the same shape with in its leaves the minimal leave value of the argument tree. Essential is that part of the result (i.e. m) is passed back as argument: data Tree = Leaf Int Bin Tree Tree deriving Show repmin :: Tree Tree repmin t = let (m, r) = repmin t m in r repmin :: Tree Int (Int, Tree) repmin (Leaf v) m = (v, Leaf m) repmin (Bin l r) m = (ml min mr, tl Bin tr) where (ml, tl) = repmin l m (mr, tr) = repmin r m 4

5 We strictify this function We can make the two-pass behaviour explicit by defining an intermediate representation: data IR rm = IR rm Int (Int Tree) repmin2 :: Tree Tree repmin2 t = case repmin2 t of IR rm m reconstruct reconstruct m repmin2 :: Tree IR rm repmin2 (Leaf v) = IR rm v Leaf repmin2 (Bin l r) = IR rm (ml min mr) (λm tfl m Bin tfr m) where (IR rm ml tfl) = repmin2 l (IR rm mr tfr) = repmin2 r 5

6 We strictify this function We can make the two-pass behaviour explicit by defining an intermediate representation: data IR rm = IR rm Int (Int Tree) repmin2 :: Tree Tree repmin2 t = case repmin2 t of IR rm m reconstruct reconstruct m repmin2 :: Tree IR rm repmin2 (Leaf v) = IR rm v Leaf repmin2 (Bin l r) = IR rm (ml min mr) (λm tfl m Bin tfr m) where (IR rm ml tfl) = repmin2 l (IR rm mr tfr) = repmin2 r 5 So far so good.

7 A complicated version of id :: Tree Tree We traverse the tree and construct a nested cartesian product of leave values together with a function which will reconstruct the tree from these values: the data IR id = vs.ir id vs (vs Tree) idtree2 :: Tree Tree idtree2 t = case idtree2 t of IR id vs reconstruct reconstruct vs 6 idtree2 :: Tree IR id idtree2 (Leaf v) = IR id v Leaf idtree2 (Bin l r) = case (idtree2 l, idtree2 r) of (IR id vsl rcl, IR id vsr rcr) IR id (vsl, vsr) (λ(vsl, vsr) rcs vsl Bin rcr vsr)

8 Translating this back to a lazy varinat If we translate this function back to a one-pass solution (compare with first version of repmin) we get: idtree :: Tree Tree idtree t = let (vs, r) = idtree t vs in r idtree (Leaf v) w = (v, Leaf w) idtree (Bin l r) (vsl, vsr ) = ((vsl, vsr), tl Bin tr) where (vsl, tl) = idtree l vsl (vsr, tr) = idtree r vsr 7

9 Translating this back to a lazy varinat If we translate this function back to a one-pass solution (compare with first version of repmin) we get: idtree :: Tree Tree idtree t = let (vs, r) = idtree t vs in r idtree (Leaf v) w = (v, Leaf w) idtree (Bin l r) (vsl, vsr ) = ((vsl, vsr), tl Bin tr) where (vsl, tl) = idtree l vsl (vsr, tr) = idtree r vsr Unfortunately this does not type-check! So the question arises why the first version of repmin is permitted, and our equivalent version of idtree is rejected? 7

10 An attempt using GADT s Our first attempt to attack the problem is by using GADT s. All the parameters and results can be described by the type: data Vals a where Leaf vals :: a Vals a Bin vals : Vals l Vals r Vals (l, r) And hence we can rewrite idtree to idtree gadt as: 8 idtree gadt :: Tree Tree idtree gadt t = let (vs, r) = idtree t vs in r idtree gadt :: Tree Vals a (Vals a, Tree) idtree gadt (Leaf v) (Leaf vals w) = (Leaf vals, Leaf w) idtree gadt (Bin l r) (Bin vals vsl vsr ) = ((Bin vals vsl vsr), tl Bin tr) where (vsl, tl) = idtree gadt l vsl (vsr, tr) = idtree gadt r vsr

11 Problems with GADT approach Unfortunately this does not work out as expected. 1. it is not allowed to lazily match on a constructor of a GADT. 2. we are less efficient since we have introduced an extra pattern 3. is is less type-safe since the following is not excluded: idtree gadt t = let (vs, r) = idtree t (convert vs) in r where convert (Leaf vals a) = Leaf vals a convert (Val bin l r) = Val leaf (lvs, rvs) where (Leaf vals lvs) = convert l (Leaf vals rvs) = convert r 9

12 What is going on? Compare the following: When calling a polymorphic function it is the context which chooses the type and then passes a value of this type, and it is the obligation of the function to honour this choice in the result it returns. In our case it is the function which chooses the type and returns a value of this type, and it is the obligation of the context to honour this choice in the arguments it passes 10

13 What is going on? Compare the following: When calling a polymorphic function it is the context which chooses the type and then passes a value of this type, and it is the obligation of the function to honour this choice in the result it returns. In our case it is the function which chooses the type and returns a value of this type, and it is the obligation of the context to honour this choice in the arguments it passes Hence the rôle of the function and the calling environment are reversed. 10

14 Solution using existential types in UHC The Utrecht Haskell Compiler (UHC) has wide support for existential types, so we can write: idtree :: Tree vs.vs (vs, Tree) idtree (Leaf v) = λw (v, Leaf w) idtree (Bin l r) = λ (vsl, vsr ) let (vsl, tl) = idtree l vsl (vsr, tr) = idtree r vsr in ((vsl, vsr), tl Bin tr) Note that the current implementation requires the explicit lambda s in the right hand sides of these alternatives. 11

15 A more useful example We want to sort a Tree and use the type system to enforce that the values in the resulting Tree were taken from the argument Tree. We first provide an implementation using lists: 12 sorttree :: Tree [Int ] [Int ] ([Int ], [Int ], Tree) sorttree t = let (vs,, res) = sorttree t [ ] vs in res insert v [ ] = [v ] insert v (w : ws) = if v < w then (v : w : w) s else (w : insert v ws) sorttree (Leaf v) rest (x : xs) = (insert v rest, xs, Leaf x) sorttree (Bin l r) rest xs = (vl, xsr, Bin tl tr) where (vl, xsl, tl) = sorttree l vr xs (vr, xsr, tr) = sorttree r rest xsl

16 ADT style equivalent We start by mimicking the use of a class dictionary; it is explicitly passed around as a field in record. This makes more explicit what is going on. Hence we define: data OrdList cl = OrdList cl (Int cl (Int, cl)) 13

17 contn d 14 sorttree :: Tree rest.ordlist rest xs.xs (OrdList xs, rest, Tree) sorttree (Leaf v) (OrdList rest insert) = λ (x, xs) (OrdList (ins v rest) (λw (x, xs) if w < x then (w, (x, xs)) else (x, insert w xs)), xs, Leaf x) sorttree (Bin l r) rest = λxs let (vl, xsl, tl) = sorttree l vr xs (vr, xsr, tr) = sorttree r rest xsl in (vl, xsr, Bin tl tr)

18 Top level call sorttree t = let (OrdList vs,, res) = sorttree t (OrdList () (λv () (v, ()))) vs in res 15

19 GHC approach Tom Schrijvers showed that using GHC s existential types in constructors we can achieve the same effect: 16 data Pack = vs.p (vs (vs, Tree)) idt :: Tree Tree idt t = case id1 t of P f let (vs, t ) = f vs in t id1 :: Tree Pack id1 (Leaf v) = P (λw (v, Leaf w)) id1 (Bin l r) = case (id1 l, id1 r) of (P f1, P f2 ) P (λ (vsl, vsr) let (vl, tl) = f1 vsl (vr, tr) = f2 vsr in ((vl, vr), Bin tl tr) )

20 Extending with classes Just as we can pass class instances implicitly when calling a polymorphic function we should be able to return class instances as part of a result: class Insertable cl where insert :: Int cl (Int, cl) instance Insertable cl Insertable (Int, cl) where insert w (x, xs) = if w < x then (w, (x, xs)) else (x, insert w xs)) instance Insertable () where insert w () = (w, ()) data OrdList cl where OrdList :: Insertable cl cl OrdList cl 17

21 Using this extension We can now write something which closely follows the types: sorttree (Leaf v) (OrdList rest) = λ (x, xs) (OrdList (insert v rest), xs, Leaf x) sorttree (Bin l r) rest = λxs let (vl, xsl, tl) = sorttree l vr xs (vr, xsr, tr) = sorttree r rest xsl in (vl, xsr, Bin tl tr) sorttree t = let (OrdList vs,, res) = sorttree t (OrdList ()) vs in res 18

22 Conclusion 1. A function takes arguments and returns results 2. A context takes results and provides arguments 3. when using lazy evaluation we need this kind of existentials 4. functions and contexts are yin and yang 5. is for contexts what is for functions 19

A Lazy Language Needs a Lazy Type System: Introducing Polymorphic Contexts

A Lazy Language Needs a Lazy Type System: Introducing Polymorphic Contexts arxiv:1612.04610v1 [cs.pl] 14 Dec 2016 A Lazy Language Needs a Lazy Type System: Introducing Polymorphic Contexts S. Doaitse Swierstra Marcos Viera Atze Dijkstra Technical Report UU-CS-2016-012 Dec 2016

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

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

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

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

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

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

Haskell, Do You Read Me?

Haskell, Do You Read Me? Haskell, Do You Read Me? Constructing and Composing Efficient Top-down Parsers at Runtime Marcos Viera Doaitse Swierstra Eelco Lempsink Instituto de Computación, Universidad de la República, Uruguay Dept.

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

Talen en Compilers. Jurriaan Hage , period 2. November 13, Department of Information and Computing Sciences Utrecht University

Talen en Compilers. Jurriaan Hage , period 2. November 13, Department of Information and Computing Sciences Utrecht University Talen en Compilers 2017-2018, period 2 Jurriaan Hage Department of Information and Computing Sciences Utrecht University November 13, 2017 1. Introduction 1-1 This lecture Introduction Course overview

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

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

Once Upon a Polymorphic Type

Once Upon a Polymorphic Type Once Upon a Polymorphic Type Keith Wansbrough Computer Laboratory University of Cambridge kw217@cl.cam.ac.uk http://www.cl.cam.ac.uk/users/kw217/ Simon Peyton Jones Microsoft Research Cambridge 20 January,

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

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

Using Strategies for Assessment of Functional Programming Exercises

Using Strategies for Assessment of Functional Programming Exercises Using Strategies for Assessment of Functional Programming Exercises Ir. Alex Gerdes Joint work with prof. dr. Johan Jeuring and dr. Bastiaan Heeren Open Universiteit Nederland School of Computer Science

More information

Course year Typeclasses and their instances

Course year Typeclasses and their instances Course year 2016-2017 Typeclasses and their instances Doaitse Swierstra and Atze Dijkstra with extra s Utrecht University September 29, 2016 1. The basics 2 Overloading versus parametric polymorphism 1

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

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph Topics Functional Programming Christian Sternagel Harald Zankl Evgeny Zuenko Department of Computer Science University of Innsbruck WS 2017/2018 abstract data types, algebraic data types, binary search

More information

Continuations and Continuation-Passing Style

Continuations and Continuation-Passing Style Continuations and Continuation-Passing Style Lecture 4 CS 390 1/16/08 Goal Weʼre interested in understanding how to represent the state of a co-routine Insight into what a thread really means How fundamental

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

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

Simon Peyton Jones Microsoft Research August 2012

Simon Peyton Jones Microsoft Research August 2012 Simon Peyton Jones Microsoft Research August 2012 A functional language Purely functional Lazy Statically typed Designed 1988-1990 By a committee For research, teaching, and practical use Geeks Practitioners

More information

Functional Programming and λ Calculus. Amey Karkare Dept of CSE, IIT Kanpur

Functional Programming and λ Calculus. Amey Karkare Dept of CSE, IIT Kanpur Functional Programming and λ Calculus Amey Karkare Dept of CSE, IIT Kanpur 0 Software Development Challenges Growing size and complexity of modern computer programs Complicated architectures Massively

More information

Introduction. Wouter Swierstra. Applied functional programming. Faculty of Science Information and Computing Sciences

Introduction. Wouter Swierstra. Applied functional programming. Faculty of Science Information and Computing Sciences Introduction Applied functional programming Wouter Swierstra 1 Welcome to the Utrecht AFP Summer School 2017 2 This morning Introduce myself and the other lecturers Overview of the course Basic Haskell

More information

Programming in Haskell

Programming in Haskell January 25, 2013 Writing Fast Haskell Laziness is both blessing and curse minimum = head. sort is O(n) for carefully-defined sort Memory usage seq, $! and bang patterns Memoization Any thunk is only ever

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

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

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

Tracing Ambiguity in GADT Type Inference

Tracing Ambiguity in GADT Type Inference Tracing Ambiguity in GADT Type Inference ML Workshop 2012, Copenhagen Jacques Garrigue & Didier Rémy Nagoya University / INRIA Garrigue & Rémy Tracing ambiguity 1 Generalized Algebraic Datatypes Algebraic

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

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

More information

Ornaments in ML. Thomas Williams, Didier Rémy. April 18, Inria - Gallium

Ornaments in ML. Thomas Williams, Didier Rémy. April 18, Inria - Gallium Ornaments in ML Thomas Williams, Didier Rémy Inria - Gallium April 18, 2017 1 Motivation Two very similar functions let rec add m n = match m with Z n S m S (add m n) let rec append ml nl = match ml with

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

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

Intermediate Code Generation

Intermediate Code Generation Intermediate Code Generation In the analysis-synthesis model of a compiler, the front end analyzes a source program and creates an intermediate representation, from which the back end generates target

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

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

Chapter 3 Linear Structures: Lists

Chapter 3 Linear Structures: Lists Plan Chapter 3 Linear Structures: Lists 1. Two constructors for lists... 3.2 2. Lists... 3.3 3. Basic operations... 3.5 4. Constructors and pattern matching... 3.6 5. Simple operations on lists... 3.9

More information

Writing code that I'm not smart enough to write. A funny thing happened at Lambda Jam

Writing code that I'm not smart enough to write. A funny thing happened at Lambda Jam Writing code that I'm not smart enough to write A funny thing happened at Lambda Jam Background "Let s make a lambda calculator" Rúnar Bjarnason Task: write an interpreter for the lambda calculus Lambda

More information

Explicit Recursion in Generic Haskell

Explicit Recursion in Generic Haskell Explicit Recursion in Generic Haskell Andres Löh Universiteit Utrecht andres@cs.uu.nl 26th March 2003 This is joint work with Dave Clarke and Johan Jeuring. Overview What is Generic Haskell? The difference

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

The design of a programming language for provably correct programs: success and failure

The design of a programming language for provably correct programs: success and failure The design of a programming language for provably correct programs: success and failure Don Sannella Laboratory for Foundations of Computer Science School of Informatics, University of Edinburgh http://homepages.inf.ed.ac.uk/dts

More information

Functional Languages and Higher-Order Functions

Functional Languages and Higher-Order Functions Functional Languages and Higher-Order Functions Leonidas Fegaras CSE 5317/4305 L12: Higher-Order Functions 1 First-Class Functions Values of some type are first-class if They can be assigned to local variables

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

Programming Language Pragmatics

Programming Language Pragmatics Chapter 10 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken Alan Turing, Alonzo Church, Stephen

More information

Lecture C-10: Parser Combinators - Introduction

Lecture C-10: Parser Combinators - Introduction Lecture C-10: Parser Combinators - Introduction USCS 2015 Doaitse Swierstra Utrecht University July 6-17, 2015 1. Domain Specific Languages 2 Domain Specific Languages 1 A DSL is a programming language

More information

Introduction. chapter Functions

Introduction. chapter Functions chapter 1 Introduction In this chapter we set the stage for the rest of the book. We start by reviewing the notion of a function, then introduce the concept of functional programming, summarise the main

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

More information

A New Foundation for Generic Programming

A New Foundation for Generic Programming Ord List A ) in The Implicit Calculus nt ) [[2, 5], [1, 3]] A New Foundation for Generic Programming 1 (presenter), Tom 2, Bruno C. d.{?(ord S.?(Ord Oliveira Schrijvers List Int with List Int )} List Int

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

An introduction to C++ template programming

An introduction to C++ template programming An introduction to C++ template programming Hayo Thielecke University of Birmingham http://www.cs.bham.ac.uk/~hxt March 2015 Templates and parametric polymorphism Template parameters Member functions of

More information

Functional Logic Programming Language Curry

Functional Logic Programming Language Curry Functional Logic Programming Language Curry Xiang Yin Department of Computer Science McMaster University November 9, 2010 Outline Functional Logic Programming Language 1 Functional Logic Programming Language

More information

Chapter 3 Linear Structures: Lists

Chapter 3 Linear Structures: Lists Plan Chapter 3 Linear Structures: Lists 1. Lists... 3.2 2. Basic operations... 3.4 3. Constructors and pattern matching... 3.5 4. Polymorphism... 3.8 5. Simple operations on lists... 3.11 6. Application:

More information

l e t print_name r = p r i n t _ e n d l i n e ( Name : ^ r. name)

l e t print_name r = p r i n t _ e n d l i n e ( Name : ^ r. name) Chapter 8 Row polymorphism Consider the following code: type name_home = {name : s t r i n g ; home : s t r i n g } type name_mobile = {name : s t r i n g ; mobile : s t r i n g } l e t jane = {name =

More information

COS 320. Compiling Techniques

COS 320. Compiling Techniques Topic 5: Types COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer 1 Types: potential benefits (I) 2 For programmers: help to eliminate common programming mistakes, particularly

More information

Arbitrary-rank polymorphism in (GHC) Haskell

Arbitrary-rank polymorphism in (GHC) Haskell Arbitrary-rank polymorphism in (GHC) Haskell CAS 743 Stephen Forrest 20 March 2006 Damas-Milner Type System A Damas-Milner type system (also called Hindley-Milner) is a traditional type system for functional

More information

CPS Translations and Applications: The Cube and Beyond

CPS Translations and Applications: The Cube and Beyond CPS Translations and Applications: The Cube and Beyond Section 2: The domain-free λ-cube Haye Böhm June 12, 2018 What we ve seen so far 1 CBV/CBN reduction strategies 2 Simulating CBN in a CBV language

More information

From Templates to Folds

From Templates to Folds From Templates to Folds CS 5010 Program Design Paradigms Bootcamp Lesson 6.3 Mitchell Wand, 2012-2014 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

More information

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

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

More information

High-performance defunctionalization in Futhark

High-performance defunctionalization in Futhark 1 High-performance defunctionalization in Futhark Anders Kiel Hovgaard Troels Henriksen Martin Elsman Department of Computer Science University of Copenhagen (DIKU) Trends in Functional Programming, 2018

More information

Compilers: The goal. Safe. e : ASM

Compilers: The goal. Safe. e : ASM Compilers: The goal What s our goal with compilers? Take a high level language, turn it into a low level language In a semantics preserving way. e : ML Safe e : ASM 1 Compilers: The goal What s our goal

More information

Lecture #23: Conversion and Type Inference

Lecture #23: Conversion and Type Inference Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). Last modified: Fri Oct 20 10:46:40 2006 CS164:

More information

CSE 3302 Programming Languages Lecture 8: Functional Programming

CSE 3302 Programming Languages Lecture 8: Functional Programming CSE 3302 Programming Languages Lecture 8: Functional Programming (based on the slides by Tim Sheard) Leonidas Fegaras University of Texas at Arlington CSE 3302 L8 Spring 2011 1 Functional Programming Languages

More information

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = Hello; Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). In Java, this is legal: Object x = "Hello";

More information

Chapter 13: Reference. Why reference Typing Evaluation Store Typings Safety Notes

Chapter 13: Reference. Why reference Typing Evaluation Store Typings Safety Notes Chapter 13: Reference Why reference Typing Evaluation Store Typings Safety Notes References Computational Effects Also known as side effects. A function or expression is said to have a side effect if,

More information

Introduction to System F. Lecture 18 CS 565 4/20/09

Introduction to System F. Lecture 18 CS 565 4/20/09 Introduction to System F Lecture 18 CS 565 4/20/09 The Limitations of F 1 (simply-typed λ- calculus) In F 1 each function works exactly for one type Example: the identity function id = λx:τ. x : τ τ We

More information

Data Types The ML Type System

Data Types The ML Type System 7 Data Types 7.2.4 The ML Type System The following is an ML version of the tail-recursive Fibonacci function introduced Fibonacci function in ML in Section 6.6.1: EXAMPLE 7.96 1. fun fib (n) = 2. let

More information

Papers we love - Utrecht

Papers we love - Utrecht Papers we love - Utrecht QuickCheck Wouter Swierstra 1 Requirements for a topic A paper that I love 2 Requirements for a topic A paper that I love A paper that is interesting to academics and developers

More information

Tradeoffs. CSE 505: Programming Languages. Lecture 15 Subtyping. Where shall we add useful completeness? Where shall we add completeness?

Tradeoffs. CSE 505: Programming Languages. Lecture 15 Subtyping. Where shall we add useful completeness? Where shall we add completeness? Tradeoffs CSE 505: Programming Languages Lecture 15 Subtyping Zach Tatlock Autumn 2017 Desirable type system properties (desiderata): soundness - exclude all programs that get stuck completeness - include

More information

First-class modules: hidden power and tantalizing promises

First-class modules: hidden power and tantalizing promises First-class modules: hidden power and tantalizing promises to GADTs and beyond Jeremy Yallop Applicative Ltd Oleg Kiselyov ML 2010 ACM SIGPLAN Workshop on ML September 26, 2010 Honestly there was no collusion

More information

The University of Nottingham

The University of Nottingham The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 1 MODULE, SPRING SEMESTER 2016-2017 PROGRAMMING PARADIGMS Time allowed: TWO hours THIRTY minutes Candidates may complete the front cover

More information

Jonathan Protzenko (INRIA)

Jonathan Protzenko (INRIA) Mezzo a typed language for safe and effectful concurrent programs Jonathan Protzenko (INRIA) jonathan.protzenko@inria.fr Jonathan Protzenko INRIA Mezzo: the defense Sept. 29th, 2014 1 / 59 This defense:

More information

CSE341 Section 3. Standard-Library Docs, First-Class Functions, & More

CSE341 Section 3. Standard-Library Docs, First-Class Functions, & More CSE341 Section 3 Standard-Library Docs, First-Class Functions, & More Adapted from slides by Daniel Snitkovskiy, Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman Agenda 1. SML Docs Standard

More information

CITS 3242 Programming Paradigms Part II. Topic 10: Imperative Programming

CITS 3242 Programming Paradigms Part II. Topic 10: Imperative Programming CITS 3242 Programming Paradigms Part II Topic 10: Imperative Programming This topic covers the background and motivations for imperative programming, as well as the imperative constructs in F# - reference

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

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

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

More information

Haskell & functional programming, some slightly more advanced stuff. Matteo Pradella

Haskell & functional programming, some slightly more advanced stuff. Matteo Pradella Haskell & functional programming, some slightly more advanced stuff Matteo Pradella pradella@elet.polimi.it IEIIT, Consiglio Nazionale delle Ricerche & DEI, Politecnico di Milano PhD course @ UniMi - Feb

More information

Monad Background (3A) Young Won Lim 11/8/17

Monad Background (3A) Young Won Lim 11/8/17 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 or any later version published

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of

More information

Type Systems, Type Inference, and Polymorphism

Type Systems, Type Inference, and Polymorphism 6 Type Systems, Type Inference, and Polymorphism Programming involves a wide range of computational constructs, such as data structures, functions, objects, communication channels, and threads of control.

More information

Simon Peyton Jones Microsoft Research August 2013

Simon Peyton Jones Microsoft Research August 2013 Simon Peyton Jones Microsoft Research August 2013 reverse :: a. [a] -> [a] xs :: [Bool] foo :: [Bool] foo = reverse xs Instantiate reverse with a unification variable, standing for an as-yet-unknown type.

More information

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees Linked representation of binary tree Again, as with linked list, entire tree can be represented with a single pointer -- in this

More information

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy 06-02552 Princ. of Progr. Languages (and Extended ) The University of Birmingham Spring Semester 2016-17 School of Computer Science c Uday Reddy2016-17 Handout 6: Polymorphic Type Systems 1. Polymorphic

More information

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

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

Faith, Evolution, and Programming Languages. Philip Wadler University of Edinburgh

Faith, Evolution, and Programming Languages. Philip Wadler University of Edinburgh Faith, Evolution, and Programming Languages Philip Wadler University of Edinburgh Evolution Multiculturalism Part I Church: The origins of faith Gerhard Gentzen (1909 1945) Gerhard Gentzen (1935) Natural

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

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

More information

(Refer Slide Time: 4:00)

(Refer Slide Time: 4:00) Principles of Programming Languages Dr. S. Arun Kumar Department of Computer Science & Engineering Indian Institute of Technology, Delhi Lecture - 38 Meanings Let us look at abstracts namely functional

More information

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming Typed Lambda Calculus Chapter 9 Benjamin Pierce Types and Programming Languages Call-by-value Operational Semantics

More information

Functional Paradigm II

Functional Paradigm II Processadors de Llenguatge II Functional Paradigm II Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra User-Defined Types How to define the new type.

More information

Polymorphic Algebraic Data Type Reconstruction

Polymorphic Algebraic Data Type Reconstruction Polymorphic Algebraic Data Type Reconstruction K.U.Leuven, Belgium {toms,maurice}@cs.kuleuven.be Namur, Belgium - December 11-15, 2006 Overview 2/39 1 2 3 4 5 6 7 Overview 3/39 1 2 3 4 5 6 7 4/39 Types

More information

Exploring Lightweight Implementations of Generics. University of Oxford Page 1

Exploring Lightweight Implementations of Generics. University of Oxford Page 1 Exploring Lightweight Implementations of Generics Bruno Oliveira University of Oxford Page 1 Introduction Generic Programming is about defining functions that can work on a family of datatypes independently

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

RepLib: A library for derivable type classes

RepLib: A library for derivable type classes RepLib: A library for derivable type classes Stephanie Weirich University of Pennsylvania Abstract Some type class instances can be automatically derived from the structure of types. As a result, the Haskell

More information

Lecture 6 Introduction to Objects and Classes

Lecture 6 Introduction to Objects and Classes Lecture 6 Introduction to Objects and Classes Outline Basic concepts Recap Computer programs Programming languages Programming paradigms Object oriented paradigm-objects and classes in Java Constructors

More information