CSE 130: Programming Languages. Polymorphism. Ranjit Jhala UC San Diego

Similar documents
Parametric types. map: ( a (a b) a list b list. filter: ( a bool) a list a list. Why? a and b are type variables!

From last time. News. Example. Example. Typechecking let. Typechecking let. Pick up your first two quizzes after class. Assignment #2 due tomorrow

Parametric types. aka: what s up with those a???

News. CSE 130: Programming Languages. Environments & Closures. Functions are first-class values. Recap: Functions as first-class values

Programming Languages. Example 5. Example 4. CSE 130 : Fall type, can reuse code for all types! let rec cat l = match l with

Programming Languages

News. Programming Languages. Recap. Recap: Environments. Functions. of functions: Closures. CSE 130 : Fall Lecture 5: Functions and Datatypes

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

Back to OCaml. Summary of polymorphism. Example 1. Type inference. Example 2. Example 2. Subtype. Polymorphic types allow us to reuse code.

Programming Languages

CSE 130 Programming Languages. Lecture 3: Datatypes. Ranjit Jhala UC San Diego

Recursion. Q: What does this evaluate to? Q: What does this evaluate to? CSE 130 : Programming Languages. Higher-Order Functions

Programming Languages

Recap: ML s Holy Trinity. Story So Far... CSE 130 Programming Languages. Datatypes. A function is a value! Next: functions, but remember.

Programming Languages

CSE 130 Programming Languages. Datatypes. Ranjit Jhala UC San Diego

Programming Languages

Programming Languages

Programming Languages

Some Advanced ML Features

Programming Languages. Tail Recursion. CSE 130: Winter Lecture 8: NOT TR. last thing function does is a recursive call

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

Programming Languages

Programming Languages

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

CSE 341 : Programming Languages Midterm, Spring 2015

Programming Languages

CSCI-GA Scripting Languages

Shell CSCE 314 TAMU. Functions continued

Mini-ML. CS 502 Lecture 2 8/28/08

Today s Plan. Programming Languages. Example : Factorial. Recursion. CSE 130 : Spring Lecture 6: Higher-Order Functions

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

Variables and Bindings

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

Monday Feb 16, 5pm. solve these equalities. Midterm Thursday Feb 12. covers only ocaml part of the course, assignments 1 through 3.

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

CS 320 Midterm Exam. Fall 2018

Generic polymorphism on steroids

Programming Languages and Techniques (CIS120)

CS 321 Programming Languages

Recap: Functions as first-class values

Programming Languages Lecture 14: Sum, Product, Recursive Types

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

CSE 130 [Winter 2014] Programming Languages

CS 11 Ocaml track: lecture 2

Programming Languages

Datatype declarations

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

Overloading, Type Classes, and Algebraic Datatypes

CS558 Programming Languages

CMSC 330, Fall 2013, Practice Problems 3

An introduction introduction to functional functional programming programming using usin Haskell

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

Programming Languages. Datatypes

Programming Languages. Next: Building datatypes. Suppose I wanted. Next: Building datatypes 10/4/2017. Review so far. Datatypes.

Programming Languages and Techniques (CIS120)

CMSC 330, Fall 2013, Practice Problem 3 Solutions

CS 457/557: Functional Languages

Recap. Recap. If-then-else expressions. If-then-else expressions. If-then-else expressions. If-then-else expressions

Exercise 1 ( = 24 points)

Recap: ML s Holy Trinity

Exercise 1 (2+2+2 points)

Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

Exercise 1 ( = 22 points)

CSE 130 [Winter 2014] Programming Languages

ML Type Inference and Unification. Arlen Cox

CSE341 Spring 2017, Midterm Examination April 28, 2017

TYPE INFERENCE. François Pottier. The Programming Languages Mentoring ICFP August 30, 2015

CSE 130, Fall 2006: Final Examination

Haskell Types, Classes, and Functions, Currying, and Polymorphism

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

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

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

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

CSE341, Fall 2011, Midterm Examination October 31, 2011

UNIVERSITETET I OSLO

Patterns The Essence of Functional Programming

CSCE 314 Programming Languages

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

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

Write: evens. evens [] ====> [] evens [1;2;3;4] ====> [2;4]

CSCI-GA Final Exam

Programming Languages and Techniques (CIS120)

List Processing in Ocaml

The Typed Racket Guide

Programming Languages

A Programming Language. A different language g is a different vision of life. CSE 130 : Fall Two variables. L1: x++; y--; (y=0)?

L3 Programming September 19, OCaml Cheatsheet

Introduction to Haskell

Programming Languages

CMSC330 Fall 2016 Midterm #1 2:00pm/3:30pm

CS558 Programming Languages

Programming Languages

Typed Racket: Racket with Static Types

02157 Functional Programming. Michael R. Ha. Lecture 2: Functions, Types and Lists. Michael R. Hansen

Next: What s in a name? Programming Languages. Data model in functional PL. What s in a name? CSE 130 : Fall Lecture 13: What s in a Name?

Transcription:

CSE 130: Programming Languages Polymorphism Ranjit Jhala UC San Diego

Q: What is the value of res? let f g = let x = 0 in g 2 let x = 100 let h y = x + y let res = f h (a) 0 (b) 2 (c) 100 (d) 102 (e) 12

Static/Lexical Scoping For each occurrence of a variable, Unique place in program text where variable defined Most recent binding in environment Static/Lexical: Determined from the program text Without executing the program Very useful for readability, debugging: Don t have to figure out where a variable got assigned Unique, statically known definition for each occurrence

Immutability: The Colbert Principle A function behaves the same way on Wednesday, as it behaved on Monday, no matter what happened on Tuesday

Polymorphism 5

News Midterm on Friday Double-sided cheat sheet Printed, if you like PA4 due NEXT Friday @ 5p First half relevant for Midterm

Polymorphism enables Reuse Can reuse generic functions: map : a * b -> b * a filter: ( a -> bool) -> a list -> a list rev: a list -> a list length: a list -> int swap: a * b -> b * a sort: ( a -> a -> bool) -> a list -> a list fold: If function (algorithm) is independent of type, can reuse code for all types

Polymorphic Data Types Data types are also polymorphic type a list = Nil Cons of ( a * a list) Type is instantiated for each use: Cons(1,Cons(2,Nil)) : Cons( a,cons( b,nil)) : Cons((1,2),Cons((3,4),Nil)) : Nil :

Polymorphic Data Types Data types are also polymorphic type a list = Nil Cons of ( a * a list) Type is instantiated for each use: Cons(1,Cons(2,Nil)) : int list Cons( a,cons( b,nil)) : string list Cons((1,2),Cons((3,4),Nil)) : (int*int) list Nil : a list

Datatypes with many type variables type ( a, b) tree = Leaf Node of a* b * ( a, b) tree * ( a, b) tree

Q: What is the type of res? type ( a, b) tree = Leaf Node of a* b * ( a, b) tree * ( a, b) tree let res = Node ( alice, 5, Leaf, Leaf) (a) (int, string) tree (b) ( a, b) tree (c) int tree (d) type error (e) (string, int) tree

Datatypes with many type variables Multiple type variables type ( a, b) tree = Leaf Node of a* b * ( a, b) tree * ( a, b) tree Type is instantiated for each use: Node( alice, 2, Leaf, Leaf) Node( charlie, 3, Leaf, Leaf) Node( bob, 13,, Node( alice, 2, Leaf, Leaf), Node( charlie, 3, Leaf, Leaf))

Q: What is the type of res? type ( a, b) tree = Leaf Node of a* b * ( a, b) tree * ( a, b) tree let res = Node( bob,13,node(3, alice,leaf, Leaf),Leaf) (a) (int, string) tree (b) ( a, b) tree (c) int tree (d) type error (e) (string, int) tree

Datatypes with many type variables Multiple type variables type ( a, b) tree = Leaf Node of a* b * ( a, b) tree * ( a, b) tree Type is instantiated for each use: Node( alice, 2, Leaf, Leaf) Node( charlie, 3, Leaf, Leaf) Node( bob, 13,, Node( alice, 2, Leaf, Leaf), Node(3, charlie, Leaf, Leaf))

A tricky question: consider this type type ( a, b) wierdlist = Nil Cons a* ( b, a) wierdlist Which is a valid Ocaml Expression? (a) Cons(1, Cons( a, Cons(3.14, Nil))) (b) Cons(1, Cons( a, Cons(1, Nil))) (c) Cons(1, Cons( a, Cons( a, Nil))) (d) Cons(1, Cons(1, Cons( a, Nil))) (e) Cons(1, Cons(1, Cons(1, Nil)))

Polymorphic Data Structures Container data structures independent of type Appropriate type is instantiated at each use: a list ( a, b) tree ( a, b) hashtbl Static type checking catches errors early Cannot add int key to string hashtable Generics: in Java,C#,VB (borrowed from ML)

Type Inference How DOES Ocaml figure out all the types?

Polymorphic Types Polymorphic types are tricky Not always obvious from staring at code How to ensure correctness? Types (almost) never entered w/ program

Polymorphic Type Inference Computing the types of all expressions At compile time : statically Typed Each binding is processed in order Types are computed for each binding For expression and variable bound to Types used for subsequent bindings Unlike values (determined at run-time)

Polymorphic Type Inference Every expression accepted by ML must have a valid inferred type Can have no idea what a function does, but still know its exact type A function may never (or sometimes terminate), but will still have a valid type

Example 1 let x = 2 + 3;; let y = string_of_int x;;

Example 2 let x = 2 + 3;; let y = string_of_int x;; let inc y = x + y;;

Whats the type of foo? let foo x = let (y, z) = x in z-y (a) int (b) int * int (c) int * int -> int (d) int -> int -> int (e) Error

Example 4 let rec cat xs = match xs with [] -> cat [] x::xs -> x^(cat xs) (a) string -> string (b) string (c) string list -> string list (d) string list -> string (e) Error

Example 5 let rec cat xs = match xs with [] -> x::xs -> x^(cat xs)

ML doesn t know what function does, or even that it finishes only its type let rec cat xs = match xs with [] -> x::xs -> x^(cat xs) let rec cat xs = match xs with [] -> cat [] x::xs -> x^(cat xs)

Example 5 let rec map f xs = match xs with [] -> [] x::xs ->(f x)::(map f xs )

Example 5 let rec map f xs = match xs with [] -> [] x::xs ->(f x)::(map f xs ) Generalize Unconstrained Vars ( a-> b) -> a list -> b list

What is the type of (<+>) let (<+>) f g x = g (f x) (a) a -> b -> c -> d (b) ( a-> b)->( a -> b)->( a -> b) (c) (int->char)->(char->bool)->(int->bool) (d) (int->int)->(int->int)->(int->int) (e) ( a-> b)->( b -> c)->( a -> c)

Example 6 let compose f g x = f (g x)

Example 7 let rec fold f cur xs = match xs with [] -> cur x::xs -> fold f (f cur x) xs

Example 7 let rec fold f cur xs = match xs with [] -> cur x::xs -> fold f (f cur x) xs

(In Class Exercise A) let rec split xs = match xs with [] -> ([], []) [x] -> ([x], []) y::z::xs -> let ys,zs = split xs in (y::ys, z::zs)

(In Class Exercise B) let rec merge xs ys = match (xs, ys) with ([],_) -> ys (_,[]) -> xs (x::xs, y::ys ) when x<=y -> x :: (merge xs ys) (x::xs, y::ys ) -> y :: (merge xs ys )

(In Class Exercise C) let rec msort xs = match xs with [] -> [] x::xs -> let ys,zs = split xs in merge (msort ys) (msort zs)

Example 11 let foo1 f g x = if f x then x else g x

Example 12 let foo2 f g x = if f x then x else foo2 f g (g x)

Binary Search Trees type ( a, b) tree = Leaf Node of a* b * ( a, b) tree * ( a, b) tree Node (key, value, left, right) BST Property: keys in left < key < keys in right

BST Property: keys in left < key < keys in right Node: bob, 13 Node: alice, 2 Node: charlie, 7 Leaf Leaf Leaf Leaf Node( bob, 13, Node( alice, 2, Leaf, Leaf), Node( charlie, 3, Leaf, Leaf))

Exercise BST Property: keys in left < key < keys in right type ( a, b) tree = Leaf Node of a* b * ( a, b) tree * ( a, b) tree Write a function to lookup keys val lookup: a ->( a, b)tree -> b option