5. Types and Polymorphism. © O. Nierstrasz PS — Type Systems 5.2 Roadmap  Static and Dynamic Types  Type Completeness  Types in Haskell  Monomorphic.

Slides:



Advertisements
Similar presentations
Functional Programming Lecture 10 - type checking.
Advertisements

ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Programming Languages and Paradigms
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap Overview:  Syntax and Semantics  Semantics of Expressions.
12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Sources  Cay Horstmann, Computing.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Introduction to Software Engineering 7. Modeling Behaviour.
CSE 341, Winter Type Systems Terms to learn about types: –Type –Type system –Statically typed language –Dynamically typed language –Type error –Strongly.
Type Checking.
Defining new types of data. Defining New Datatypes Ability to add new datatypes in a programming language is important. Kinds of datatypes – enumerated.
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap  Syntax and Semantics  Semantics of Expressions 
6. Introduction to the Lambda Calculus. © O. Nierstrasz PS — Introduction to the Lambda Calculus 6.2 Roadmap  What is Computability? — Church’s Thesis.
12. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Roadmap  Summary: —Trends in programming paradigms  Research:...
4. Functional Programming. © O. Nierstrasz PS — Functional Programming 4.2 Roadmap Overview  Functional vs. Imperative Programming  Pattern Matching.
Functional Design and Programming Lecture 1: Functional modeling, design and programming.
ESE Einführung in Software Engineering N. XXX Prof. O. Nierstrasz Fall Semester 2009.
13. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Summary, Trends, Research...  Summary: functional, logic and object-oriented.
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
7. Fixed Points. © O. Nierstrasz PS — Fixed Points 7.2 Roadmap  Representing Numbers  Recursion and the Fixed-Point Combinator  The typed lambda calculus.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Comp 205: Comparative Programming Languages User-Defined Types Enumerated types Parameterised types Recursive types Lecture notes, exercises, etc., can.
Metamodeling Seminar X. CHAPTER Prof. O. Nierstrasz Spring Semester 2008.
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
N. XXX Prof. O. Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes.
7. Fixed Points. © O. Nierstrasz PS — Fixed Points 7.2 Roadmap Overview  Representing Numbers  Recursion and the Fixed-Point Combinator  The typed.
4. Functional Programming. © O. Nierstrasz PS — Functional Programming 4.2 Roadmap  Functional vs. Imperative Programming  Pattern Matching  Referential.
7. Fixed Points. © O. Nierstrasz PS — Fixed Points 7.2 Roadmap  Representing Numbers  Recursion and the Fixed-Point Combinator  The typed lambda calculus.
12. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Roadmap  Summary: —Trends in programming paradigms  Research:...
Type Inference: CIS Seminar, 11/3/2009 Type inference: Inside the Type Checker. A presentation by: Daniel Tuck.
CP — Concurrent Programming X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
Chapter 12 Qualified Types. Motivation  What should the principal type of (+) be? Int -> Int -> Int-- too specific a -> a -> a-- too general  It seems.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 19: Functions, Types and Data Structures in Haskell COMP 144 Programming Language.
12. eToys. © O. Nierstrasz PS — eToys 12.2 Denotational Semantics Overview:  … References:  …
Imperative Programming
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
CSE 425: Data Types II Survey of Common Types I Records –E.g., structs in C++ –If elements are named, a record is projected into its fields (e.g., via.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
1 Functional Programming Lecture 6 - Algebraic Data Types.
Overview of the Haskell 98 Programming Language
CS5205Haskell1 CS5205: Foundations in Programming Languages FP with Haskell A pure lazy functional language that embodies many innovative ideas in language.
© M. Winter COSC 4P41 – Functional Programming Modules in Haskell Using modules to structure a large program has a number of advantages: Parts of.
12/9/20151 Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC Based in part on slides by Mattox.
Homogeneous tuples What are they? –S 2 = S x S –S n = S x S x … x S Cardinalities –#(S 2 )= (#S) 2 –#(S n )= (#S) n –#(S 0 )= (#S) 0 =1 What is S 0 ? –It.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
COMP 412, FALL Type Systems II C OMP 412 Rice University Houston, Texas Fall 2000 Copyright 2000, Robert Cartwright, all rights reserved. Students.
Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. L05-1 September 21, 2006http:// Types and Simple Type.
Dr. M. Al-Mulhem Introduction 1 Chapter 6 Type Systems.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Type Checking and Type Inference
Programming Languages and Compilers (CS 421)
Principles of programming languages 12: Functional programming
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
Haskell Chapter 2.
CS 326 Programming Languages, Concepts and Implementation
A lightening tour in 45 minutes
Type Systems Terms to learn about types: Related concepts: Type
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Types and Classes in Haskell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
PROGRAMMING IN HASKELL
Type Systems Terms to learn about types: Related concepts: Type
PROGRAMMING IN HASKELL
Presentation transcript:

5. Types and Polymorphism

© O. Nierstrasz PS — Type Systems 5.2 Roadmap  Static and Dynamic Types  Type Completeness  Types in Haskell  Monomorphic and Polymorphic types  Hindley-Milner Type Inference  Overloading

© O. Nierstrasz PS — Type Systems 5.3 References  Paul Hudak, “Conception, Evolution, and Application of Functional Programming Languages,” ACM Computing Surveys 21/3, Sept. 1989, pp  L. Cardelli and P. Wegner, “On Understanding Types, Data Abstraction, and Polymorphism,” ACM Computing Surveys, 17/4, Dec. 1985, pp  D. Watt, Programming Language Concepts and Paradigms, Prentice Hall, 1990

© O. Nierstrasz PS — Type Systems 5.4 Roadmap  Static and Dynamic Types  Type Completeness  Types in Haskell  Monomorphic and Polymorphic types  Hindley-Milner Type Inference  Overloading

© O. Nierstrasz PS — Type Systems 5.5 What is a Type? Type errors: A type is a set of values?  int = {... -2, -1, 0, 1, 2, 3,... }  bool = { True, False }  Point = { [x=0,y=0], [x=1,y=0], [x=0,y=1]... } ? 5 + [ ] ERROR: Type error in application *** expression : 5 + [ ] *** term : 5 *** type : Int *** does not match : [a]

© O. Nierstrasz PS — Type Systems 5.6 What is a Type? A type is a partial specification of behaviour?  n,m:int  n+m is valid, but not(n) is an error  n:int  n := 1 is valid, but n := “hello world” is an error What kinds of specifications are interesting? Useful?

© O. Nierstrasz PS — Type Systems 5.7 Static and Dynamic Types Values have static types defined by the programming language. A variable may have a declared, static type. Variables and expressions have dynamic types determined by the values they assume at run-time. Applet myApplet = new GameApplet(); declared, static type is Applet static type of value is GameApplet actual dynamic type is GameApplet

© O. Nierstrasz PS — Type Systems 5.8 Static types restrict the programs you may write! Program text Syntax ok Semantics ok Static types ok Object wyatt = new Cowboy(); wyatt.draw();

© O. Nierstrasz PS — Type Systems 5.9 Static and Dynamic Typing A language is statically typed if it is always possible to determine the (static) type of an expression based on the program text alone. A language is dynamically typed if only values have fixed type. Variables and parameters may take on different types at run-time, and must be checked immediately before they are used. A language is “strongly typed” if it is impossible to perform an operation on the wrong kind of object. Type consistency may be assured by I. compile-time type-checking, II. type inference, or III. dynamic type-checking.

© O. Nierstrasz PS — Type Systems 5.10 Strong, weak, static, dynamic StaticDynamic “Strong”Java, PascalSmalltalk, Ruby “Weak”CAssembler

© O. Nierstrasz PS — Type Systems 5.11 Kinds of Types All programming languages provide some set of built-in types.  Primitive types: booleans, integers, floats, chars...  Composite types: functions, lists, tuples... Most strongly-typed modern languages provide for additional user-defined types.  User-defined types: enumerations, recursive types, generic types, objects...

© O. Nierstrasz PS — Type Systems 5.12 Roadmap  Static and Dynamic Types  Type Completeness  Types in Haskell  Monomorphic and Polymorphic types  Hindley-Milner Type Inference  Overloading

© O. Nierstrasz PS — Type Systems 5.13 Type Completeness The Type Completeness Principle: No operation should be arbitrarily restricted in the types of values involved. — Watt First-class values can be evaluated, passed as arguments and used as components of composite values. Functional languages attempt to make no class distinctions, whereas imperative languages typically treat functions (at best) as second-class values.

© O. Nierstrasz PS — Type Systems 5.14 Roadmap  Static and Dynamic Types  Type Completeness  Types in Haskell  Monomorphic and Polymorphic types  Hindley-Milner Type Inference  Overloading

© O. Nierstrasz PS — Type Systems 5.15 Function Types Function types allow one to deduce the types of expressions without the need to evaluate them: fact :: Int -> Int 42 :: Int  fact 42 :: Int Curried types: Int -> Int -> Int  Int -> (Int -> Int) and plus 5 6  ((plus 5) 6) so: plus::Int->Int->Int  plus 5::Int->Int

© O. Nierstrasz PS — Type Systems 5.16 List Types A list of values of type a has the type [a]: [ 1 ] :: [ Int ] NB: All of the elements in a list must be of the same type! ['a', 2, False]-- illegal! can’t be typed!

© O. Nierstrasz PS — Type Systems 5.17 Tuple Types If the expressions x1, x2,..., xn have types t1, t2,..., tn respectively, then the tuple (x1, x2,..., xn) has the type (t1, t2,..., tn): (1, [2], 3) :: (Int, [Int], Int) ('a', False) :: (Char, Bool) ((1,2),(3,4)) :: ((Int, Int), (Int, Int)) The unit type is written () and has a single element which is also written as ().

© O. Nierstrasz PS — Type Systems 5.18 User Data Types New data types can be introduced by specifying I. a datatype name, II. a set of parameter types, and III. a set of constructors for elements of the type: where the constructors may be either: 1. Named constructors: 2. Binary constructors (i.e., anything starting with “:”): data DatatypeName a1... an = constr1 |... | constrm Name type1... typek type1 BINOP type2

© O. Nierstrasz PS — Type Systems 5.19 Enumeration types User data types that do not hold any data can model enumerations: Functions over user data types must deconstruct the arguments, with one case for each constructor: data Day = Sun | Mon | Tue | Wed | Thu | Fri | Sat whatShallIDo Sun= “relax” whatShallIDo Sat= “go shopping” whatShallIDo _= “guess I'll have to go to work”

© O. Nierstrasz PS — Type Systems 5.20 Union types data Temp = Centigrade Float | Fahrenheit Float freezing :: Temp -> Bool freezing (Centigrade temp)= temp <= 0.0 freezing (Fahrenheit temp)= temp <= 32.0

© O. Nierstrasz PS — Type Systems 5.21 Recursive Data Types A recursive data type provides constructors over the type itself: data Tree a = Lf a | Tree a :^: Tree a mytree = (Lf 12 :^: (Lf 23 :^: Lf 13)) :^: Lf 10 ? :t mytree  mytree :: Tree Int

© O. Nierstrasz PS — Type Systems 5.22 Using recursive data types  What do these functions do?  Which function should be more efficient? Why?  What is (l:) and what does it do? NB: (f. g) x = f (g x) leaves, leaves' :: Tree a -> [a] leaves (Lf l)= [l] leaves (l :^: r)= leaves l ++ leaves r leaves' t = leavesAcc t [ ] where leavesAcc (Lf l) = (l:) leavesAcc (l :^: r) = leavesAcc l. leavesAcc r

© O. Nierstrasz PS — Type Systems 5.23 Roadmap  Static and Dynamic Types  Type Completeness  Types in Haskell  Monomorphic and Polymorphic types  Hindley-Milner Type Inference  Overloading

© O. Nierstrasz PS — Type Systems 5.24 Monomorphism Languages like Pascal and C have monomorphic type systems: every constant, variable, parameter and function result has a unique type.  good for type-checking  bad for writing generic code —it is impossible in Pascal to write a generic sort procedure

© O. Nierstrasz PS — Type Systems 5.25 Polymorphism A polymorphic function accepts arguments of different types: length:: [a] -> Int length [ ]= 0 length (x:xs)= 1 + length xs map:: (a -> b) -> [a] -> [b] map f [ ]= [ ] map f (x:xs)= f x : map f xs (.):: (b -> c) -> (a -> b) -> (a -> c) (f. g) x= f (g x)

© O. Nierstrasz PS — Type Systems 5.26 Roadmap  Static and Dynamic Types  Type Completeness  Types in Haskell  Monomorphic and Polymorphic types  Hindley-Milner Type Inference  Overloading

© O. Nierstrasz PS — Type Systems 5.27 Type Inference We can infer the type of many expressions by simply examining their structure. Consider: Clearly: length :: a -> b Furthermore, b is obvious int, and a is a list, so: length :: [c] -> int We cannot further refine the type, so we are done. length [ ]= 0 length (x:xs)= 1 + length xs

© O. Nierstrasz PS — Type Systems 5.28 Composing polymorphic types We can deduce the types of expressions using polymorphic functions by simply binding type variables to concrete types. Consider: length:: [a] -> Int map:: (a -> b) -> [a] -> [b] Then: map length:: [[a]] -> [Int] [ “Hello”, “World” ]:: [[Char]] map length [ “Hello”, “World” ]:: [Int]

© O. Nierstrasz PS — Type Systems 5.29 Polymorphic Type Inference Hindley-Milner Type Inference automatically determines the types of many polymorphic functions. The corresponding type system is used in many modern functional languages, including ML and Haskell. mapf[ ]=[ ] mapf(x:xs)=f x : map f xs map::X->Y ->Z map::(a -> b)->-> [ c ] [ a ] [ d ] [ b ]

© O. Nierstrasz PS — Type Systems 5.30 Type Specialization A polymorphic function may be explicitly assigned a more specific type: Note that the :t command can be used to find the type of a particular expression that is inferred by Haskell: idInt :: Int -> Int idInt x = x ? :t \x -> [x]  \x -> [x] :: a -> [a] ? :t (\x -> [x]) :: Char -> String  \x -> [x] :: Char -> String

© O. Nierstrasz PS — Type Systems 5.31 Kinds of Polymorphism  Universal polymorphism: —Parametric: polymorphic map function in Haskell; nil/void pointer type in Pascal/C —Inclusion: subtyping — graphic objects  Ad Hoc polymorphism: —Overloading: + applies to both integers and reals —Coercion: integer values can be used where reals are expected and v.v.

© O. Nierstrasz PS — Type Systems 5.32 Roadmap  Static and Dynamic Types  Type Completeness  Types in Haskell  Monomorphic and Polymorphic types  Hindley-Milner Type Inference  Overloading

© O. Nierstrasz PS — Type Systems 5.33 Coercion vs overloading Coercion or overloading — how do you distinguish?  Are there several overloaded + functions, or just one, with values automatically coerced?

© O. Nierstrasz PS — Type Systems 5.34 Overloading Overloaded operators are introduced by means of type classes: A type class must be instantiated to be used: class Eq a where (==), (/=) :: a -> a -> Bool x /= y= not (x == y) -- NB: defined in standard prelude instance Eq Bool where True == True= True False == False= True _ == _= False

© O. Nierstrasz PS — Type Systems 5.35 Instantiating overloaded operators For each overloaded instance a separate definition must be given instance Eq Int where (==)= primEqInt instance Eq Char where c == d= ord c == ord d instance (Eq a, Eq b) => Eq (a,b) where (x,y) == (u,v)= x==u && y==v instance Eq a => Eq [a] where [ ] == [ ]= True [ ] == (y:ys)= False (x:xs) == [ ]= False (x:xs) == (y:ys)= x==y && xs==ys

© O. Nierstrasz PS — Type Systems 5.36 Equality for Data Types Why not automatically provide equality for all types of values? User data types:  How would you define equality for the Tree data type? NB: all (‘elem’ ys) xs tests that every x in xs is an element of ys data Set a = Set [a] instance Eq a => Eq (Set a) where Set xs == Set ys = xs `subset` ys && ys `subset` xs where xs `subset` ys = all (`elem` ys) xs

© O. Nierstrasz PS — Type Systems 5.37 Equality for Functions Functions: Determining equality of functions is undecidable in general! ? (1==) == (\x->1==x) ERROR: Cannot derive instance in expression *** Expression : (==) d148 ((==) {dict} 1) (\x->(==) {dict} 1 x) *** Required instance : Eq (Int -> Bool)

© O. Nierstrasz PS — Type Systems 5.38 What you should know!  How are the types of functions, lists and tuples specified?  How can the type of an expression be inferred without evaluating it?  What is a polymorphic function?  How can the type of a polymorphic function be inferred?  How does overloading differ from parametric polymorphism?  How would you define == for tuples of length 3?  How can you define your own data types?  Why isn’t == pre-defined for all types?

© O. Nierstrasz PS — Type Systems 5.39 Can you answer these questions?  Can any set of values be considered a type?  Why does Haskell sometimes fail to infer the type of an expression?  What is the type of the predefined function all? How would you implement it?  How would you define equality for the Tree data type?

© Oscar Nierstrasz ST — Introduction 1.40 Attribution-ShareAlike 3.0 Unported You are free: to Share — to copy, distribute and transmit the work to Remix — to adapt the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license. For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page. Any of the above conditions can be waived if you get permission from the copyright holder. Nothing in this license impairs or restricts the author's moral rights. License