860 likes | 874 Views
CSED321 Programming Languages Polymorphism. Kyungmin Bae Department of Computer Science and Engineering POSTECH Spring 2019. Polymorphism. Parametric Polymorphism operates on all types of objects in a uniform way. C++ templates, Java generics, … Subtype Polymorphism
E N D
CSED321 Programming LanguagesPolymorphism Kyungmin Bae Department of Computer Science and Engineering POSTECH Spring 2019
Polymorphism • Parametric Polymorphism • operates on all types of objects in a uniform way. • C++ templates, Java generics, … • Subtype Polymorphism • operates on subtypes of objects • subtypes on classes • Ad hoc Polymorphism • different behavior depending on the type of objects it operates on • operator overloading
Outline • System F • Programming in System F • Type reconstruction • Implicit polymorphism • Type inference algorithm
System F • Untyped -calculus + Parametric polymorphism • First step toward the polymorphic type system of OCaml
Type of • Bind variable to some type • Decide the type of the resulting expression • In the simply typed -calculus:
Type of : Goal • Bind variable to any type • Assign a polymorphic type to
Type Abstraction • Declares as a fresh any type, or a fresh type variable
Type Application • Type application • Example
Type Safety • Type preservation If and , then • Progress If for some type , then either is a value or there exists such that
Outline • System F • Programming in System F • Type reconstruction • Implicit polymorphism • Type inference algorithm
Power of System F • Can naturally encode complex data types • C.f. simply typed lambda calculus
Programming in System F: Numerals • Type • zero • succ
Programming in System F: Product Types • Type • pair • fst • snd
Programming in System F: Sum Types • Type • inl • inr • case
Strong Normalization • Every expression in System F eventually reduces to a value.
Outline • System F • Programming in System F • Type reconstruction • Implicit polymorphism • Type inference algorithm
Which is the Most Readable? fun f -> fun g -> (fun x -> g (f x)) fun f : ('a -> ‘b) -> fun g : ('b -> ‘c) -> (fun x : 'a -> g (f x)) fun f : ('a -> ‘b) -> fun g : ('b -> ‘c) -> ((fun x : 'a -> (g (f x)) : 'c): 'a -> 'c)
Type Reconstruction • From: untyped (typeable) program • To: typed program
Bad News • Not every untyped expression is typeable in System F • Type reconstruction of System F is undecidable
Predicative Polymorphic -Calculus • Sublanguage of System F • Decidable type reconstruction • Supports polymorphism
Types in Predicative Polymorphic -Calculus • A polytype in prenex form
Let-Polymorphism • System F • Powerful, but undecidable type reconstruction • Predicative polymorphic -Calculus • Decidable type reconstruction, but useless • Let-Polymorphism • Decidable type reconstruction, and useful
Let-Binding • binds to a polymorphic expression • not a syntactic sugar in terms of types!