08 Recursive Parameterized Variants

Variants can be recursive and parameterized.

Let's write our own type for lists of integers.

Here we have a recursive consructor. Our Cons constructor includes intlist.

We can write a length function.

Now let's take the length of an int list!

Now we have an int list with the first element 1, and the second element 2.

Now what if the next day we decided we also wanted to implement string lists. One possibility would be to repeat all of this code, but the issue with that would be shadowing, so we'd need to change names. This won't scale well at all.

Whenever you're copying and pasting code, you pretty much doing something wrong. Rather than copying and pasting codes, good programmers extract ideas and parameterize this.

How do we do this? We use a parameterized variant:

Now we have a better version of our list! We have a variant type! We can use 'a in this definition wherever we want.

Now let's write a length function for mylist.

We could also make our syntax nicer!

Look at that! It has a type of int mylist

And our length function works well too :)

In fact, this is exactly how the standard library implements lists:

type 'a list = [] | (::) of 'a * 'a list

That's it. list is a type constructor parameterized on the type variable 'a. [] and :: are just constructors of the variant.