0% found this document useful (0 votes)
16 views44 pages

4 Types

Uploaded by

kavithakr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views44 pages

4 Types

Uploaded by

kavithakr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Principles of Programming

Languages
Types and Type classes in Haskell

S6CSE, Department of CSE, Amritapuri


Haskell Type
• Haskell has a static type system.
• The type of every expression is known at compile time, which leads to safer
code.
• Haskell has type inference.
• It can infer that on its own, so we don't have to explicitly write out the types of
our functions and expressions
• A type is a kind of label that every expression has. It tells us in which
category of things that expression fits.

S6CSE, Department of CSE, Amritapuri


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:

False True

S6CSE, Department of CSE, Amritapuri


Type Errors
• Applying a function to one or more arguments of the wrong type is
called a type error.

> 1 + False
ERROR

1 is a number and False is a logical


value, but + requires two numbers.

S6CSE, Department of CSE, Amritapuri


Types in Haskell
• A type is: a way to prevent errors
• A type is: a method of organization & documentation
• A type is: a hint to the compiler

A type is a kind of label that every expression has. It tells us in which


category of things that expression fits. The expression True is a boolean,
"hello" is a string, etc.

S6CSE, Department of CSE, Amritapuri


Types in Haskell
• If evaluating an expression e would produce a value of type t, then e has
type t, written

• Every well-formed expression has a type, which can be automatically


calculated at compile time using a process called type inference.
• Unlike Java or Pascal, Haskell has type inference. If we write a number,
we don't have to tell Haskell it's a number. It can infer that on its own, so
we don't have to explicitly write out the types of our functions and
expressions to get things done.

S6CSE, Department of CSE, Amritapuri
Haskell type

:t on an expression prints out the


expression followed by :: and its
type. :: is read as "has type of".

S6CSE, Department of CSE, Amritapuri


Types in Haskell
• All type errors are found at compile time, which makes programs safer
and faster by removing the need for type checks at run time.
• In GHCi, the :type or :t command calculates the type of an expression,
without evaluating it:

> not False


True

> :type not False


not False :: Bool

S6CSE, Department of CSE, Amritapuri


Basic Types
• Haskell has several basic types, including:
Bool - logical values
Char - single characters
String - strings of characters
Int - fixed-precision integers
Integer - arbitrary-precision integers
Float - floating-point numbers
S6CSE, Department of CSE, Amritapuri
Int and Integer
• Int stands for integer. It's used for whole numbers.
• 7 can be an Int but 7.2 cannot.
• Int is bounded, which means that it has a minimum and a maximum value.
[Usually on 32-bit machines the maximum possible Int is 2147483647 and the
minimum is -2147483648].

• Integer
• The main difference is that it's not bounded so it can be used to represent
really big numbers.

S6CSE, Department of CSE, Amritapuri


Bool Type
• The boolean type Bool is an enumeration.
• Values
• True
• False

• The basic boolean functions are


• && (and)
• || (or)
• not

S6CSE, Department of CSE, Amritapuri


Char and String Type
• The character type Char is an enumeration whose values represent
Unicode characters.
• Type Char is an instance of the classes Read, Show, Eq, Ord, Enum, and
Bounded.
• The toEnum and fromEnum functions, standard functions from class
Enum, map characters to and from the Int type.
• A string is a list of characters: type String = [Char]
• Strings may be abbreviated using the lexical syntax.
• For example, "A string" abbreviates
[ 'A',' ','s','t','r', 'i','n','g']
S6CSE, Department of CSE, Amritapuri
List types
• A list is sequence of values of the same type:
[False,True,False] :: [Bool]

[’a’,’b’,’c’,’d’] :: [Char]

• In general:
• [t] is the type of lists with elements of type t.

S6CSE, Department of CSE, Amritapuri


Note:
• The type of a list says nothing about its length:
[False,True] :: [Bool]

[False,True,False] :: [Bool]
• The type of the elements is unrestricted. For example, we can have
lists of lists:
[[’a’],[’b’,’c’]] :: [[Char]]

S6CSE, Department of CSE, Amritapuri


Tuple Types
• A tuple is a sequence of values of different types:
(False,True) :: (Bool,Bool)

(False,’a’,True) :: (Bool,Char,Bool)

• In general:
• (t1,t2,…,tn) is the type of n-tuples whose ith components have type ti for any i
in 1…n.

S6CSE, Department of CSE, Amritapuri


Note:-
• A tuple is fixed in size so we cannot alter it, but List can grow as
elements get added.
• The elements of a tuple do not need to be all of the same types, but the
list stores only the same type of values.

S6CSE, Department of CSE, Amritapuri


Note:-
• The type of a tuple encodes its size:
(False,True) :: (Bool,Bool)

(False,True,False) :: (Bool,Bool,Bool)

• The type of the components is unrestricted:

(’a’,(False,’b’)) :: (Char,(Bool,Char))

(True,[’a’,’b’]) :: (Bool,[Char])

S6CSE, Department of CSE, Amritapuri


Function Types
• A function is a mapping from values of one type to values of another
type :

In general
t1 → t2 is the type of functions that map values of type t1 to
values to type t2.

S6CSE, Department of CSE, Amritapuri


Function Types
• Functions also have type signatures. In Haskell an -> is used to
separate arguments and return values.

S6CSE, Department of CSE, Amritapuri


Function Type
• The argument and result types are unrestricted.
For example, functions with multiple arguments or results are possible
using lists or tuples:

S6CSE, Department of CSE, Amritapuri


Type variables
• What is this a?
• Is it a type? - it's actually a type variable means that a can be of any type.
• It's much more powerful because it allows us to easily write very general
functions if they don't use any specific behavior of the types in them.
• Functions that have type variables are called polymorphic functions.
• The type declaration of head states that it takes a list of any type and
returns one element of that type.
• Type variables can have names longer than one character, we usually
give them names of a, b, c, d …

S6CSE, Department of CSE, Amritapuri


Polymorphic Functions
• A function is called polymorphic (“of many forms”) if its type contains one or
more type variables.
length :: [a]  Int

for any type a, length takes a list of


values of type a and returns an integer.
• Type variables can be instantiated to different types in different circumstances:
• Type variables must begin with a lower-case letter, and are usually named a, b,
c, etc
S6CSE, Department of CSE, Amritapuri
Polymorphic Functions
• Many of the functions defined in the standard prelude are
polymorphic. For example:

S6CSE, Department of CSE, Amritapuri


Overloaded Functions
• A polymorphic function is called overloaded if its type contains one or
more class constraints.
sum :: Num a  [a]  a

for any numeric type a, sum


takes a list of values of type a
and returns a value of type a.

S6CSE, Department of CSE, Amritapuri


• Constrained type variables can be instantiated to any types that satisfy
the constraints:
> sum [1,2,3] a = Int
6

> sum [1.1,2.2,3.3] a = Float


6.6

> sum [’a’,’b’,’c’] Char is not a


ERROR numeric type
S6CSE, Department of CSE, Amritapuri
 Haskell has a number of type classes, including:

Num - Numeric types


Eq - Equality types
Ord - Ordered types

 For example:
(+) :: Num a  a  a  a
(==) :: Eq a  a  a  Bool
(<) :: Ord a  a  a  Bool
26
Hints and Tips

• When defining a new function in Haskell, it is useful


to begin by writing down its type;

• Within a script, it is good practice to state the type of


every new function defined;

• When stating the types of polymorphic functions that


use numbers, equality or orderings, take care to
include the necessary class constraints.

27
Haskell Typeclasses

S6CSE, Department of CSE, Amritapuri


TYPE CLASSES
• Type classes allow you to group types based on shared behavior.
• A type class states which function a type must support in the same way
that an interface specifies which method a class must support.
• Type classes are the heart of Haskell programming.
• Type classes may remind you of interfaces in Java.

S6CSE, Department of CSE, Amritapuri


What's the type signature of the == function?

• Everything before the => symbol is called a class constraint.


• The Eq typeclass provides an interface for testing for equality.
• Any type where it makes sense to test for equality between two values
of that type should be a member of the Eq class.
• All standard Haskell types except for IO (the type for dealing with
input and output) and functions are a part of the Eq typeclass.
• The elem function has a type of (Eq a) => a -> [a] -> Bool because it
uses == over a list to check whether some value we're looking for is in
it.

S6CSE, Department of CSE, Amritapuri


Why Type classes?
• Each function defined works for only one specific set of types.
• Without type classes, you’d need a different name for each function
that adds a different type of value.
• They allow us to declare which types are instances of which class, and
to provide definitions of the overloaded operations associated with a
class.

S6CSE, Department of CSE, Amritapuri


Basic Typeclasses

• Eq: equality
• Ord: comparison
• Num: numerical operations
• Show: convert to string
• Read: convert from string
• Testable, Arbitrary: testing.
• Enum: ops on sequentially ordered types
• Bounded: upper and lower values of a type
• Generic programming, reflection, monads, …
• And many more.

S6CSE, Department of CSE, Amritapuri


Functions in
type classes

S6CSE, Department of CSE, Amritapuri


An example
Let’s look at the Num typeclass in
Haskell:
• For a type to belong to
the Num typeclass, it needs to
implement its methods: +, -, *, and
so forth.
• That is +, can only be used on types
that have an instance of Num.
• A function that uses + needs to limit
itself by only taking
members of the Num typeclass.
Otherwise, it won’t compile.

S6CSE, Department of CSE, Amritapuri


Common Type Classes used
• Ord
• Eq
• Num
• Show

S6CSE, Department of CSE, Amritapuri


Eq
• The Eq type class needs only two
functions: == and /=.
• If you can tell that two types are
equal or not equal, that type
belongs in the Eq type class.

S6CSE, Department of CSE, Amritapuri


Ord
• Take any two of the same types that
implement Ord and return a
Boolean.
• Ord covers all the standard
comparing functions such as >, <,
To be a member of Ord, a type must first
>= and <=.
have membership in the prestigious and
• The compare function takes two Ord exclusive Eq club.
members of the same type and
returns an ordering. Ordering is a
type that can be GT, LT or EQ,
meaning greater than, lesser than and
equal, respectively.
S6CSE, Department of CSE, Amritapuri
Show
• The show function turns a value Every time a value is printed in
into a String. GHCi, it’s printed because it’s a
member of the Show type class.
• All types covered so far except
for functions are a part of Show.
• The most used function that
deals with the Show typeclass is
show. It takes a value whose type
is a member of Show and
presents it to us as a string.

S6CSE, Department of CSE, Amritapuri


• what happens if we try to do just
Read read "4“.

• Read is sort of the opposite


typeclass of Show. • It knows we want some type that
• The read function takes a string is part of the Read class, it just
and returns a type which is a doesn't know which one. So, use
member of Read. type annotations.

S6CSE, Department of CSE, Amritapuri


Num
• Num is a numeric typeclass. Its • It appears that whole numbers
members have the property of are also polymorphic constants.
being able to act like numbers. They can act like any type that's
a member of the Num typeclass.

S6CSE, Department of CSE, Amritapuri


Enum
• Enum members are sequentially
ordered types — they can be
enumerated.
• The main advantage of the Enum
typeclass is that we can use its types
in list ranges.
• They also have defined successors
and predecesors, which you can get
with the succ and pred functions.
• Types in this class: (), Bool, Char,
Ordering, Int, Integer, Float and
Double.
S6CSE, Department of CSE, Amritapuri
Polymorphism
• Type classes are the way you use polymorphism in Haskell

S6CSE, Department of CSE, Amritapuri


Type class in Haskell’s standard library
Arrows from one class to another indicate a superclass relationship

S6CSE, Department of CSE, Amritapuri


Next - Functions

S6CSE, Department of CSE, Amritapuri

You might also like