*This preview shows
pages
1–3. Sign up
to
view the full content.*

10/6/10
1
Kathleen Fisher
cs242
Thanks to Simon Peyton Jones for some of these slides.
Reading: “Concepts in Programming Languages”,
New Chapter 7, Type Classes
Parametric polymorphism
Single algorithm may be given
many
types
Type variable may be replaced by
any
type
if
f::t
→
t
then
f::Int
→
Int
,
f::Bool
→
Bool
, .
..
Overloading
A single symbol may refer to
more than one
algorithm.
Each algorithm may have different type.
Choice of algorithm determined by type context.
+ has types
Int
→
Int
→
Int
and
Float
→
Float
→
Float
,
but not
t
→
t
→
t
for arbitrary
t
.
Many useful functions are not parametric.
Can member work for any type?
No!
Only for types
w
for that support
equality
.
Can sort work for any type?
No!
Only for types
w
that support
ordering
.
member :: [w] -> w -> Bool
sort :: [w] -> [w]
Many useful functions are not parametric.
Can serialize work for any type?
No!
Only for types
w
that support
serialization
.
Can sumOfSquares work for any type?
No!
Only for types that support
numeric operations
.
serialize:: w -> String
sumOfSquares:: [w] -> w
Allow functions containing overloaded symbols to
de±ne multiple functions:
But consider:
This approach has not been widely used because
of
exponential growth
in number of versions.
square x = x * x
-- legal
-- Defines two versions:
-- Int -> Int and Float -> Float
squares (x,y,z) =
(square x, square y, square z)
-- There are 8 possible versions!
First Approach
Basic operations such as + and * can be overloaded,
but not functions de±ned in terms of them.
Standard ML uses this approach.
Not satisfactory
: Why should the language be able to
de±ne overloaded operations, but not the programmer?
3 * 3
-- legal
3.14 * 3.14
-- legal
square x = x * x
-- Int -> Int
square 3
-- legal
square 3.14
-- illegal
Second Approach

This
** preview**
has intentionally

**sections.**

*blurred***to view the full version.**

*Sign up* 10/6/10
2
Equality defned
only
For types that
admit equality
:
types not containing Function or abstract types.
Overload equality like arithmetic ops + and * in SML.
But then we
can’t defne Functions using ‘==‘
:
Approach adopted in frst version oF SML.
3 * 3 == 9
-- legal
‘a’ == ‘b’
-- legal
\x->x == \y->y+1
-- illegal
member [] y
= False
member (x:xs) y = (x==y) || member xs y
member [1,2,3] 3
-- ok if default is Int
member “Haskell” ‘k’
-- illegal
±irst Approach
Make equality Fully polymorphic.
Type oF member Function:
Miranda used this approach.
Equality applied to a Function yields a
runtime error
.
Equality applied to an abstract type compares the
underlying representation, which
violates abstraction
principles
.
(==) :: a -> a -> Bool
member :: [a] -> a -> Bool
Second Approach
Make equality polymorphic in a limited way:
where
a
(==)
is a type variable ranging
only
over types
that admit equality.
Now we can type the member Function:

This is the end of the preview. Sign up
to
access the rest of the document.