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.

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

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.

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.

Reverse A List, Polymorphic & Recursive Function

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.