Lecture 13-1
Polymorphic Types
Some functions accept many different types. An example of this is length
which accepts many different types of lists.
if you ask what the type of then function length
is then it will return the type:
length :: [a] -> Int
a
is a type variable. This means that:
- The function can be applied to any list.
a
will represent the type of list elements.
This type is called polymorphism. This is a feature of functional languages.
Type Variables
In the function head
it will return the type variable which it was given in the list. Hence asking for the type returns:
head :: [a] -> a
Type variables can appear more than once. These types specify that the return type will be determined by the type of the input.
Multiple type variables can be included in one declaration for example the function fst
returns the following:
fst :: (a,b) -> a
As a result the types of function can tell you a lot about what the function does.
Type Annotations
Is it good practice to insert type annotations for your functions. This is so that Haskell assigns the types to your functions that you expect. You do this with the following syntax.
f :: Int -> Int
f x = x + 1
The annotation is usually place before the function definition. If you don’t give a type annotation, then Haskell will infer one for you based on the functions used in your function. This is a result of the language being strongly typed.
Annotating your function can make it easier to catch bugs. This will give the compiler more to work with and make errors more descriptive.
Exercises
take :: Int -> [a] -> [a]
(:) :: a -> [a] -> [a]
(++) :: [a] -> [a] -> [a]