Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a...

69
Polymorphism and Classes Functional Programming and Reasoning Dr Hans Georg Schaathun University of Surrey Spring 2010 Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 1 / 37

Transcript of Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a...

Page 1: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Polymorphism and ClassesFunctional Programming and Reasoning

Dr Hans Georg Schaathun

University of Surrey

Spring 2010

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 1 / 37

Page 2: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Outline

1 Algebraic Datatypes

2 Polymorphism

3 Classes of types

4 Summary

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 2 / 37

Page 3: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

This session

After this session, you shouldunderstand the concepts of overloading and polymorphismunderstand how polymorphism can make software developmentfaster and simplerunderstand the concept of classes in haskell, and be able to useclasses to generalise definitionshave a brief understanding of the use of algebraic data types

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 3 / 37

Page 4: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Warnings

Polymorphism is a general concept.and it is called polymorphism also in Java.

Java classes are not classes; they are data typesthe Java analog of a class is the ensemble of a class and all itsderived classes

A class is an ensemble of data types (with similar properties)this use of the word class is not particular to functionalprogrammingAda has the same terminology, and is object-oriented andimperative

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 4 / 37

Page 5: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes

Outline

1 Algebraic DatatypesEnumerated TypesProduct typesFunctions

2 Polymorphism

3 Classes of types

4 Summary

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 5 / 37

Page 6: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Enumerated Types

Defining your own data types

Haskell allows user-defined data typesthese are usually algebraic data types

The simplest form is enumerated typesjust listing each possible data type

For instancedata Season = Spring | Summer | Autumn | Winterdata Faculty = FEPS | FAHS | FML | FHMS

The elements (Spring etc.) are called constructorsa constructor, when called, creates (‘constructs’) a new data object

Constructure names always start with a capital

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 6 / 37

Page 7: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Enumerated Types

Functions on enumerated types

Functions can be defined for each possible value

weather :: Season -> Stringweather Spring = "Sunny"weather Summer = "Warm"weather Autumn = "Wet"weather Winter = "Cold"

Or wild-cards can be used

weather :: Season -> Stringweather Summer = "Warm"weather _ = "Cold"

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 7 / 37

Page 8: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Enumerated Types

Functions on enumerated types

Functions can be defined for each possible value

weather :: Season -> Stringweather Spring = "Sunny"weather Summer = "Warm"weather Autumn = "Wet"weather Winter = "Cold"

Or wild-cards can be used

weather :: Season -> Stringweather Summer = "Warm"weather _ = "Cold"

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 7 / 37

Page 9: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Enumerated Types

Strings vs. Enumerated type

Consider a Staff database(Surname, First Name, DoB, Faculty)

What data type for Faculty?String?

"FEPS", "FMS", etc.Enumerated?

data Faculty = FEPS | FMS | ...

and why?

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 8 / 37

Page 10: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Enumerated Types

Strings vs. Enumerated type

Advantages of Enumerated data typesType checking – cannot be mistaken for another StringCompact storage and fast comparison

Disadvantages of Enumerated data typesReprogramming required to add a faculty

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37

Page 11: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Enumerated Types

Strings vs. Enumerated type

Advantages of Enumerated data typesType checking – cannot be mistaken for another StringCompact storage and fast comparison

Disadvantages of Enumerated data typesReprogramming required to add a faculty

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37

Page 12: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Enumerated Types

Strings vs. Enumerated type

Advantages of Enumerated data typesType checking – cannot be mistaken for another StringCompact storage and fast comparison

Disadvantages of Enumerated data typesReprogramming required to add a faculty

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37

Page 13: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Enumerated Types

Strings vs. Enumerated type

Advantages of Enumerated data typesType checking – cannot be mistaken for another StringCompact storage and fast comparison

Disadvantages of Enumerated data typesReprogramming required to add a faculty

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37

Page 14: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Product types

Product data types

The simplest product data type would bedata Length = Feet Intheight :: Lengthheight = Feet 6

Why do we use a special data type?Why not just Int?

The type Length cannot be confused with IntA function defined on Int does not work on Lengthand vice versa

Such strong typing will catch many bugs

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 10 / 37

Page 15: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Product types

Product data types

The simplest product data type would bedata Length = Feet Intheight :: Lengthheight = Feet 6

Why do we use a special data type?Why not just Int?

The type Length cannot be confused with IntA function defined on Int does not work on Lengthand vice versa

Such strong typing will catch many bugs

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 10 / 37

Page 16: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Product types

Product data types

The simplest product data type would bedata Length = Feet Intheight :: Lengthheight = Feet 6

Why do we use a special data type?Why not just Int?

The type Length cannot be confused with IntA function defined on Int does not work on Lengthand vice versa

Such strong typing will catch many bugs

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 10 / 37

Page 17: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Product types

Product data types

The simplest product data type would bedata Length = Feet Intheight :: Lengthheight = Feet 6

Why do we use a special data type?Why not just Int?

The type Length cannot be confused with IntA function defined on Int does not work on Lengthand vice versa

Such strong typing will catch many bugs

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 10 / 37

Page 18: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Product types

More product data types

Product data types is an alternative to tuplesdata Person = Id String Intp :: Personp = Id "John Smith" 42

Suppose we need feet and inches for the lengthdata Length = Feet Int Intheight :: Lengthheight = Feet 5 10

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 11 / 37

Page 19: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Product types

More product data types

Product data types is an alternative to tuplesdata Person = Id String Intp :: Personp = Id "John Smith" 42

Suppose we need feet and inches for the lengthdata Length = Feet Int Intheight :: Lengthheight = Feet 5 10

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 11 / 37

Page 20: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Product types

Product data types in general

Combine enumeration and product types

data Shape =Circle Float |Rectangle Float Float |Triangle Float Float Float

For a Circle the Radius is givenFor Rectangle: height + widthFor Triangle (e.g.): width (base line), height, angle (lower leftcorner)

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 12 / 37

Page 21: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Functions

Functions on algebraic typesPattern matching again

We need a function for the area of a Shapearea :: Shape -> Float

Function definition based on pattern matchingDefine a function for each pattern

area (Circle r) = pi*rˆ2 (pi defined by the Prelude)area (Rectangle x y) = x * yarea (Triangle x y _) = x*y/2

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 13 / 37

Page 22: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Functions

Functions on algebraic typesPattern matching again

We need a function for the area of a Shapearea :: Shape -> Float

Function definition based on pattern matchingDefine a function for each pattern

area (Circle r) = pi*rˆ2 (pi defined by the Prelude)area (Rectangle x y) = x * yarea (Triangle x y _) = x*y/2

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 13 / 37

Page 23: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Functions

Example of product data typesStaff record

Recall the tuple: (Surname, First Name, DoB, Faculty)Surname and First name are StringsWhat data type for Date of Birth?Algebraic?

data Date = Dat Int Int Int

data Faculty = FEPS | FAHS | FML | FHMS

data Person = Pers String String Date Faculty

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 14 / 37

Page 24: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Functions

Example of product data typesStaff record

Recall the tuple: (Surname, First Name, DoB, Faculty)Surname and First name are StringsWhat data type for Date of Birth?Algebraic?

data Date = Dat Int Int Int

data Faculty = FEPS | FAHS | FML | FHMS

data Person = Pers String String Date Faculty

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 14 / 37

Page 25: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Functions

Example of product data typesStaff record

Recall the tuple: (Surname, First Name, DoB, Faculty)Surname and First name are StringsWhat data type for Date of Birth?Algebraic?

data Date = Dat Int Int Int

data Faculty = FEPS | FAHS | FML | FHMS

data Person = Pers String String Date Faculty

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 14 / 37

Page 26: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Functions

Example of product data typesStaff record

Recall the tuple: (Surname, First Name, DoB, Faculty)Surname and First name are StringsWhat data type for Date of Birth?Algebraic?

data Date = Dat Int Int Int

data Faculty = FEPS | FAHS | FML | FHMS

data Person = Pers String String Date Faculty

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 14 / 37

Page 27: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Algebraic Datatypes Functions

Example of product data typesStaff record

Recall the tuple: (Surname, First Name, DoB, Faculty)Surname and First name are StringsWhat data type for Date of Birth?Algebraic?

data Date = Dat Int Int Int

data Faculty = FEPS | FAHS | FML | FHMS

data Person = Pers String String Date Faculty

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 14 / 37

Page 28: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Polymorphism

Outline

1 Algebraic Datatypes

2 PolymorphismPolymorphism

3 Classes of types

4 Summary

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 15 / 37

Page 29: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Polymorphism Polymorphism

Polymorphism

polymorphism ∼ «has many shapes»

Polymorphic functions apply to different types of dataFor instance the length of a list

length :: [a] -> Intwhere a is a type variablei.e. a matches any type

Or concatenation(++) :: [a] -> [a] -> [a]a is an arbitrary typebut all three instances of a are the same type

Polymorphism saves us the trouble of typing several similardefinitions

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 16 / 37

Page 30: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Polymorphism Polymorphism

Polymorphism

polymorphism ∼ «has many shapes»

Polymorphic functions apply to different types of dataFor instance the length of a list

length :: [a] -> Intwhere a is a type variablei.e. a matches any type

Or concatenation(++) :: [a] -> [a] -> [a]a is an arbitrary typebut all three instances of a are the same type

Polymorphism saves us the trouble of typing several similardefinitions

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 16 / 37

Page 31: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Polymorphism Polymorphism

Polymorphism

polymorphism ∼ «has many shapes»

Polymorphic functions apply to different types of dataFor instance the length of a list

length :: [a] -> Intwhere a is a type variablei.e. a matches any type

Or concatenation(++) :: [a] -> [a] -> [a]a is an arbitrary typebut all three instances of a are the same type

Polymorphism saves us the trouble of typing several similardefinitions

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 16 / 37

Page 32: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Polymorphism Polymorphism

Polymorphic implementationFor example

The length function could be defined as

length :: [a] -> Intlength [] = 0length (x:xs) = 1 + length xs

This is an example of recursion over lists

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 17 / 37

Page 33: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Polymorphism Polymorphism

Polymorphic implementationFor example

The length function could be defined as

length :: [a] -> Intlength [] = 0length (x:xs) = 1 + length xs

This is an example of recursion over lists

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 17 / 37

Page 34: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Polymorphism Polymorphism

Polymorphism versus Overloading

Polymorphism and Overloading both allowsame function name on different types

However, there is a key differencePolymorphism has a single function definition

applicable to several typesOverloading allows different definitions

for different types

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 18 / 37

Page 35: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Polymorphism Polymorphism

Polymorphism versus Overloading

Polymorphism and Overloading both allowsame function name on different types

However, there is a key differencePolymorphism has a single function definition

applicable to several typesOverloading allows different definitions

for different types

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 18 / 37

Page 36: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Polymorphism Polymorphism

Polymorphism versus Overloading

Polymorphism and Overloading both allowsame function name on different types

However, there is a key differencePolymorphism has a single function definition

applicable to several typesOverloading allows different definitions

for different types

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 18 / 37

Page 37: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Polymorphism Polymorphism

Polymorphism versus Overloading

Polymorphism and Overloading both allowsame function name on different types

However, there is a key differencePolymorphism has a single function definition

applicable to several typesOverloading allows different definitions

for different types

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 18 / 37

Page 38: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types

Outline

1 Algebraic Datatypes

2 Polymorphism

3 Classes of typesSome simple examplesHow to overloadThe Show classDeriving classes

4 Summary

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 19 / 37

Page 39: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Some simple examples

What is a class?

First: do not confuse it with a Java class.A class is a collection of types

common propertiescertain functions or operations defined

In Java and C++, a class is one typethe closest Java equivalent is probably interfaces

Both meanings are commonAda classes are similar to Haskell’s

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 20 / 37

Page 40: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Some simple examples

What is a class?

First: do not confuse it with a Java class.A class is a collection of types

common propertiescertain functions or operations defined

In Java and C++, a class is one typethe closest Java equivalent is probably interfaces

Both meanings are commonAda classes are similar to Haskell’s

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 20 / 37

Page 41: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Some simple examples

What is a class?

First: do not confuse it with a Java class.A class is a collection of types

common propertiescertain functions or operations defined

In Java and C++, a class is one typethe closest Java equivalent is probably interfaces

Both meanings are commonAda classes are similar to Haskell’s

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 20 / 37

Page 42: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Some simple examples

An example class

isMatch :: ( Eq a ) => (a,a) -> BoolisMatch (x,y) = x == y

( Eq a ) => : a restricted to class EqEq is a class of types with equality

== is definedThe polymorphic function can call ==

we do not know the type abut we know that == is defined

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 21 / 37

Page 43: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Some simple examples

Other classes

Ord : <, >, etc. are definedShow : convertible to a String (show function)Num : numeric: +, −, ×, etc. defined... and user-defined classesYou will often need built-in classes for your polymorphism

... there is an example in the exercises.

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 22 / 37

Page 44: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Some simple examples

Other classes

Ord : <, >, etc. are definedShow : convertible to a String (show function)Num : numeric: +, −, ×, etc. defined... and user-defined classesYou will often need built-in classes for your polymorphism

... there is an example in the exercises.

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 22 / 37

Page 45: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Some simple examples

Other classes

Ord : <, >, etc. are definedShow : convertible to a String (show function)Num : numeric: +, −, ×, etc. defined... and user-defined classesYou will often need built-in classes for your polymorphism

... there is an example in the exercises.

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 22 / 37

Page 46: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Some simple examples

Sorting functions

Sorting lists is a common task ...[x1, x2, . . . , xn]such that ∀i , xi ≤ xi+1

When does this make sense?when ≤ is defined ...

sort :: ( Ord a ) => [a] -> [a]

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 23 / 37

Page 47: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Some simple examples

Sorting functions

Sorting lists is a common task ...[x1, x2, . . . , xn]such that ∀i , xi ≤ xi+1

When does this make sense?when ≤ is defined ...

sort :: ( Ord a ) => [a] -> [a]

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 23 / 37

Page 48: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Some simple examples

Sorting functions

Sorting lists is a common task ...[x1, x2, . . . , xn]such that ∀i , xi ≤ xi+1

When does this make sense?when ≤ is defined ...

sort :: ( Ord a ) => [a] -> [a]

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 23 / 37

Page 49: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types How to overload

User-defined classes... or how to achieve overloading

Reconsider the exercises of Week 2, where you madecapitaliseChar :: Char -> CharcapitaliseString :: String -> String

Would it not be easier with an overloaded function?capitalise :: a -> a

Not straight forward,you cannot just define capitalise twicewith different type declarations

Classes allow you to do it.Define capitilise twicelinked to different class instances

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 24 / 37

Page 50: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types How to overload

User-defined classes... or how to achieve overloading

Reconsider the exercises of Week 2, where you madecapitaliseChar :: Char -> CharcapitaliseString :: String -> String

Would it not be easier with an overloaded function?capitalise :: a -> a

Not straight forward,you cannot just define capitalise twicewith different type declarations

Classes allow you to do it.Define capitilise twicelinked to different class instances

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 24 / 37

Page 51: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types How to overload

User-defined classes... or how to achieve overloading

Reconsider the exercises of Week 2, where you madecapitaliseChar :: Char -> CharcapitaliseString :: String -> String

Would it not be easier with an overloaded function?capitalise :: a -> a

Not straight forward,you cannot just define capitalise twicewith different type declarations

Classes allow you to do it.Define capitilise twicelinked to different class instances

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 24 / 37

Page 52: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types How to overload

Capitalising Characters and StringsDefining the class

class Cap a wherecapitalise :: a -> a

The class has one property:a function capitalise is defined

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 25 / 37

Page 53: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types How to overload

Capitalising Characters and StringsDefining an instance

instance Cap Char wherecapitalise x | b < 97 = x

| b > 122 = x| otherwise = toEnum ((fromEnum x) - 32)

where b = fromEnum x

Char becomes an instance of CapProvide a definition for each function declared in the class

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 26 / 37

Page 54: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types How to overload

Capitalising Characters and StringsDefining a polymorphic instance

instance Cap a => Cap [a] wherecapitalise = map capitalise

Polymorphic instanceValid for any list type [a]

if the constituent type a is an instance of Cap

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 27 / 37

Page 55: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types How to overload

Class and InstanceAnother example

A new class can be defined as follows

class MyClass a wheremyFunction :: [a] -> a

an existing datatype can be made an instance of the class

instance MyClass Int wheremyFunction xs = foldr1 (+) xs

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 28 / 37

Page 56: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types How to overload

Polymorphic InstancesAnother example

The definition of myFunction would apply to any numberThus a polymorphic instance is possible:

instance Num a => MyClass a wheremyFunction xs = foldr1 (+) xs

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 29 / 37

Page 57: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types The Show class

Standard functionsPrintable types (Show)

New types are not printable by default... not members of the Show class

now :: Season

Main> nowERROR - Cannot find "show" function for:

*** Expression : now

*** Of type : Season

This is cumbersome when you test functionsHow do you solve this?

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 30 / 37

Page 58: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types The Show class

Making it printableInstance of Show

1 Make an instance2 Define the show function

show :: a -> String

instance Show Season whereshow Summer = "Summer"show Spring = "Spring"show Winter = "Winter"show Autumn = "Fall"

Do you need other classes?

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 31 / 37

Page 59: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Deriving classes

Common classes

Some classes should cover most data typesOrd, Eq, Show, etc.

Simple, straight-forward definitionsHaskell can create instances automatically

you just need to askThe deriving key word does the job.

data Season = Spring | Summer | Autumn | Winterderiving Eq

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 32 / 37

Page 60: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Deriving classes

Common classes

Some classes should cover most data typesOrd, Eq, Show, etc.

Simple, straight-forward definitionsHaskell can create instances automatically

you just need to askThe deriving key word does the job.

data Season = Spring | Summer | Autumn | Winterderiving Eq

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 32 / 37

Page 61: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Deriving classes

Common classes

Some classes should cover most data typesOrd, Eq, Show, etc.

Simple, straight-forward definitionsHaskell can create instances automatically

you just need to askThe deriving key word does the job.

data Season = Spring | Summer | Autumn | Winterderiving Eq

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 32 / 37

Page 62: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Deriving classes

Common classes

Some classes should cover most data typesOrd, Eq, Show, etc.

Simple, straight-forward definitionsHaskell can create instances automatically

you just need to askThe deriving key word does the job.

data Season = Spring | Summer | Autumn | Winterderiving Eq

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 32 / 37

Page 63: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Deriving classes

Making it printableA short-cut

data Season = Spring | Summer | Autumn | Winterderiving Show

In this case the string shown would be the constructor

Main> SpringSpring

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 33 / 37

Page 64: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Deriving classes

Deriving multiple classes

Several classes may be derivedRemember parentheses!

data Season = Spring | Summer | Autumn | Winterderiving (Eq, Show)

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 34 / 37

Page 65: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Deriving classes

Ordering

data Season = Spring | Summer | Autumn | Winter deriving Ord

Ordering on enumerated types may be usefuluse guards to treat different groups of values differently

deriving does not solve all problemsFor product types you often want to define your own ordering

to make sure that the right elements are compared

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 35 / 37

Page 66: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Deriving classes

Ordering

data Season = Spring | Summer | Autumn | Winter deriving Ord

Ordering on enumerated types may be usefuluse guards to treat different groups of values differently

deriving does not solve all problemsFor product types you often want to define your own ordering

to make sure that the right elements are compared

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 35 / 37

Page 67: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Classes of types Deriving classes

Ordering

data Season = Spring | Summer | Autumn | Winter deriving Ord

Ordering on enumerated types may be usefuluse guards to treat different groups of values differently

deriving does not solve all problemsFor product types you often want to define your own ordering

to make sure that the right elements are compared

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 35 / 37

Page 68: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Summary

Outline

1 Algebraic Datatypes

2 Polymorphism

3 Classes of types

4 Summary

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 36 / 37

Page 69: Polymorphism and Classes · Disadvantages of Enumerated data types Reprogramming required to add a faculty Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 9 / 37. Algebraic

Summary

Summary

We have presented a number of powerful techniques for functiondesign

PolymorphismOverloadingClasses – as a tool for overloading and polymorphismUser-defined types – Algebraic Datatypes

General techniques – applies in many formsStudy the exercises

if you cannot do the exercises... you will struggle with the exam too

Dr Hans Georg Schaathun Polymorphism and Classes Spring 2010 37 / 37