Chapter 12 Qualified Types. Motivation  What should the principal type of (+) be? Int -> Int -> Int-- too specific a -> a -> a-- too general  It seems.

Slides:



Advertisements
Similar presentations
Types and Programming Languages Lecture 13 Simon Gay Department of Computing Science University of Glasgow 2006/07.
Advertisements

Cs776 (Prasad)L4Poly1 Polymorphic Type System. cs776 (Prasad)L4Poly2 Goals Allow expression of “for all types T” fun I x = x I : ’a -> ’a Allow expression.
Logic & program control part 2: Simple selection structures.
0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
String is a synonym for the type [Char].
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
CSE 341, Winter Type Systems Terms to learn about types: –Type –Type system –Statically typed language –Dynamically typed language –Type error –Strongly.
COMP150PLD Thanks to Simon Peyton Jones for some of these slides. Reading: “Concepts in Programming Languages”, New Chapter 7, Type Classes; “How to make.
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
Cse536 Functional Programming 1 6/12/2015 Lecture #11, Nov. 01, 2004 Special Guest lecture by Tom Harke Today’s Topics –The Haskell Class system –Instance.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
A Lightning Tour of Haskell Lecture 1, Designing and Using Combinators John Hughes.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
Cse536 Functional Programming 1 6/23/2015 Lecture #17, Dec. 1, 2004 Todays Topics – Higher Order types »Type constructors that take types as arguments.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Type Inference: CIS Seminar, 11/3/2009 Type inference: Inside the Type Checker. A presentation by: Daniel Tuck.
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
1 COMP313A Programming Languages Functional Programming (7)
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
VARIABLES AND TYPES CITS1001. Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Scope.
Operators, Functions and Modules1 Pattern Matching & Recursion.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
CS5205Haskell1 CS5205: Foundations in Programming Languages FP with Haskell A pure lazy functional language that embodies many innovative ideas in language.
What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type Bool contains the two logical values: True.
© M. Winter COSC 4P41 – Functional Programming Modules in Haskell Using modules to structure a large program has a number of advantages: Parts of.
Kathleen Fisher cs242 Thanks to Simon Peyton Jones for some of these slides.
CS321 Functional Programming 2 © JAS CS321 Functional Programming 2 Dr John A Sharp 10 credits Tuesday 10amRobert Recorde Room Thursday 11amRobert.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Overloading operators C++ incorporates the option to use standard operators to perform operations with.
Do-it-yourself dictionaries in Haskell1 Ingmar Brouns & Lukas Spee.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Hindley-Milner Type Inference CSE 340 – Principles of Programming Languages Fall 2015 Adam Doupé Arizona State University
Haskell. GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
Defining Classes Modules and ADTs CSCE 314 Spring 2016.
Cs776(Prasad)L6sml971 SML-97 Specifics SML/NJ 110.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Polymorphic Functions
Functional Programming
String is a synonym for the type [Char].
Principles of programming languages 12: Functional programming
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
Haskell Chapter 2.
MPCS 51400: Functional Programming
CSE 3302 Programming Languages
Type & Typeclass Syntax in function
Types and Classes in Haskell
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
Records and Type Classes
Chapter 6 Section 5.
PROGRAMMING IN HASKELL
CSEP505: Programming Languages Lecture 9: Haskell Typeclasses and Monads; Dan Grossman Autumn 2016.
Type Systems Terms to learn about types: Related concepts: Type
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Records and Type Classes
Presentation transcript:

Chapter 12 Qualified Types

Motivation  What should the principal type of (+) be? Int -> Int -> Int-- too specific a -> a -> a-- too general  It seems like we need something “in between”, that restricts “a” to be from the set of all number types, say Num = {Int, Integer, Float, Double, etc.}.  Recall that the type signature a -> a -> a is really shorthand for ( ∀ a) a -> a -> a  Qualified types generalize this by qualifying the type variable, as in ( ∀ a ∈ Num) a -> a -> a, which in Haskell we write as Num a => a -> a -> a

Type Classes  “Num” in the previous example is called a type class, and should not be confused with a type constructor or a value constructor.  “Num T” should be read “T is a member of (or an instance of) the type class Num”.  Haskell’s type classes are one of its most innovative features.  This capability is also called “overloading”, because one function name is used for potentially very different purposes.  There are many pre-defined type classes, but you can also define your own.

Example: Equality  Like addition, equality is not defined on all types (how do we test the equality of two functions, for example?).  So the equality operator (==) in Haskell has type Eq a => a -> a -> Bool. For example: 42 == 42  True `a` == `a`  True `a` == 42  > (types don’t match) (+1) == (\x->x+1)  > ((->) is not an instance of Eq)  Note: the type errors occur at compile time!

Equality, cont’d  Eq is defined by this type class declaration: class Eq a where (==), (/=) :: a -> a -> Bool x /= y = not (x == y) x == y = not (x /= y)  The last two lines are default methods for the operators defined to be in this class.  A type is made an instance of a class by an instance declaration. For example: instance Eq Int where x == y= intEq x y-- primitive equality for Ints instance Eq Float where x == y= floatEq x y-- primitive equality for Floats

Equality, cont’d  But user-defined data types can also be made instances of Eq. For example: data Tree a = Leaf a | Branch (Tree a) (Tree a) instance Eq (Tree a) where Leaf a1 == Leaf a2 = a1 == a2 Branch l1 r1 == Branch l2 r2 = l1==l2 && r1==r2 _ == _ = False  But something is strange here: is “a1 == a2” on the right-hand side correct? How do we know that equality is defined on the type “a”???

Equality, cont’d  But user-defined data types can also be made instances of Eq. For example: data Tree a = Leaf a | Branch (Tree a) (Tree a) instance Eq a => Eq (Tree a) where Leaf a1 == Leaf a2 = a1 == a2 Branch l1 r1 == Branch l2 r2 = l1==l2 && r1==r2 _ == _ = False  But something is strange here: is “a1 == a2” on the right-hand side correct? How do we know that equality is defined on the type “a”???  Solution: Introduce a constraint on “a”, namely that it also be an instance of the type class Eq.

Constraints / Contexts are Propagated  Consider this function: x `elem` [] = False x `elem` (y:ys) = x==y || x `elem` ys  Note the use of (==) on the right-hand side of the second equation. So the principal type for elem is: elem :: Eq a => a -> [a] -> Bool  This is inferred automatically by Haskell, but as always, it is recommended that you provide your own type signature for all functions.

Example from Regions  Useful slogan: “polymorphism captures similar structure over different values, while type classes capture similar operations over different structures.”  For a simple example, recall from Chapter 8: containsS :: Shape -> Point -> Bool containsR :: Region -> Point -> Bool  These are similar ops over different structures. So: class PC t where contains :: t -> Point -> Bool instance PC Shape where contains = containsS instance PC Region where contains = containsR

Numeric Classes  Haskell’s numeric types are embedded in a very rich, hierarchical set of type classes.  For example, the Num class is defined by: class (Eq a, Show a) => Num a where (+), (-), (*) :: a -> a -> a negate :: a -> a abs, signum :: a -> a fromInteger :: Integer -> a  Where Show is a type class whose main operator is show :: Show a => a -> String  See the Numeric Class Hierarchy in the Haskell Report on the next slide.

Haskell’s Numeric Class Hierarchy

Coercions  Note this method in the class Num: fromInteger :: Num a => Integer -> a  Also, in the class Integral: toInteger :: Integral a => a -> Integer  This explains the definition of intToFloat: intToFloat :: Int -> Float intToFloat n = fromInteger (toInteger n)  These generic coercion functions avoid a quadratic blowup in the number of coercion functions.  Also, every integer literal, say “42”, is really shorthand for “fromInteger 42”, thus allowing that number to be typed as any member of Num.

Derived Instances  Instances of the following type classes may be automatically derived: Eq, Ord, Enum, Bounded, Ix, Read, and Show  This is done by adding a deriving clause. For example: data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving (Show, Eq)  This will automatically create an instance for Show (Tree a) as well as one for Eq (Tree a) that is precisely equivalent to the one we defined earlier.

Reasoning About Type Classes  Most type classes implicitly carry a set of laws.  For example, the Eq class is expected to obey: (a /= b) = not (a == b) (a == b) && (b == c) ⊇ (a == c)  Similarly, for the Ord class: a <= a (a <= b) && (b <= c) ⊇ (a <= c) (a <= b) && (b <= a) ⊇ (a == b) (a /= b) ⊇ (a < b) || (b < a)  These laws capture the properties of an equivalence class and a total order, respectively.  Unfortunately, there is nothing in Haskell that enforces the laws – its up to the programmer!