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.

-- 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

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 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.

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

Reverse A List, Polymorphic & Recursive Function

-- 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.

Leave a Reply
You May Also Like

What Is The Difference Between An Object & A Variable (JAVA)

In Java there’s a few different things; Objects, Classes and Variables to…

What is a Java Interface?

Java contains Interfaces, Classes and Objects. Distinguishing between each can be slightly…

How To Use Bootstrap to Make CPA Landing Pages

CPA landing pages can often be tedious and difficult to make, especially…

Forex Money Management: How to Manage Your Money when Trading Forex

I’m not a finance professional, don’t take my advice, this article is…