I decided to reimplement some basic functions and structures in OCaml from scratch as an exercise. I usually do this in a Jupyter notebook but I took my notes and I will be publishing them in my blog from now on (as a way to remember where I put that bloody notebook). You can practice and redo this samples with the Jupyter kernel for OCaml, in fact, I already have a small docker image with it ready for you to try if you want to, go and pull it from Docker Hub.

The definition of sequences

Let’s start defining a sequence, we will call it seq:

type'aseq=|End|Nextof'a*'aseq

Out[*]:

type 'a seq = Nil | Next of 'a * 'a seq

As you can see we use a generic parameter 'a for the value of the sequence. We can create a sequence with numbers from 0 to 3 and an empty sequence:

Interestinly, this function had the potential to use the inner accumulator loop but if we see clearly it is not needed, remember, if we discard the value of a function when it returns in a recursive call it is basically tail recursive, and here we do nothing with the return value of the function until we need it.

An easy way to check if a function call is tail recursive is asking the compiler to tell us so (available since OCaml 4.04)