Post Contents

Polymorphic types are types that are “universally quantified in some way over all types“.

What a mouthful.

Basically, it makes it so we can use a certain variable/bit of data without worry about the type conflicts.

Recursion on the other hand, refers to a function that calls its self again and again.

## A simple example, a length function

This function will demonstrate both a polymorphic function and recursive function.

1 2 3 4 5 |
-- This program will use polymorphic types and a little bit of recursion too! length :: [a] -> Integer -- here's our function length [] = 0 -- a simple base case length (x:xs) = 1 + length xs -- the recursive bit |

We define the function a some list of “a” input, that returns an Integer.

Then, the base case is simply to say 0, because an empty list “[]” has length 0.

And finally, the last part, **the recursive call**

- (x:xs)Β is a form of pattern matching
- x where there is some xs left behind it
- Here’s simple idea behind the recursion
- length [a,b,c,d] = 1 + length [b,c,d]
- length [b,c,d] = 1 + length [c,d]
- length [c,d] = 1 + length [d]
- length [d] = 1 + length []
- length [] = 0

- length [d] = 1 + length []

- length [c,d] = 1 + length [d]

- length [b,c,d] = 1 + length [c,d]

- length [a,b,c,d] = 1 + length [b,c,d]

**1 is added 4 times over, and finalised at 0.**

1+1+1+1+0 = 4.

## A List Head function, polymorphic

If you want to return the head of a list of integers you could go for the easy route.

1 2 3 4 |
-- This program returns the head of a list of integers headOfList :: [Integer] -> Integer headOfList (x:xs) = x |

This works perfectly fine.But what if you don’t know the type of the list?

Well, of course it breaks.

So we need polymorphic types to make it work.

1 2 |
polyMorphicListHead :: [a] -> a polyMorphicListHead (x:xs) = x |

## Reverse A List, Polymorphic & Recursive Function

1 2 3 4 5 6 |
-- This programme will reverse a list of any type reverser :: [a] -> [a] -- declaring function.. reverser [] = [] -- base case for empty list reverser [x] = [x] -- general case for singleton list reverser (x:xs) = reverser(xs) ++ [x] -- recursive case |

The reverser function reduces the list all the way down the last element, then slowly appends the head of each list back.

***

That’s all for now, more haskell tutorials coming shortly.

Until next time, Josh.