Climbing the functional ladder
Introduction
After this weekend's Christmas post, I thought it would be good to go back to some more grounded content. Today I want to talk about a new obsession of mine: functional programming. This isn't the first post that touches upon it: I've been very enthusiastic about Gleam. I've reconnected with OCaml, so now it's time to tie this all together.
Functional programming: what is it?
Defining functional programming correctly and clearly is in and of itself a difficult exercise. Not that there isn't a definition, but in my experience, functional programming is immensely tied to very abstract academic topics (did someone say category theory?) and might look scary at first glance (god my first Haskell encounter was horrifying).
What made it click for me was this excellent post (which you can also find on my Linklog). I will not just retell the content of the post (I likely wouldn't do it justice anyway), so I encourage you to read it. If you're impatient, maybe in a train or bus somewhere and don't have time for yet another link, don't fret. This post will still give you the gist of it.
What a lot of people just call programming is itself a style called imperative programming. It's tradition to use the Fibonacci sequence for basic examples, so let's not break tradition here. Imperative programming is about describing the how of a program. You declare a set of instructions, and follow their execution.
fn imperative_fibonacci(n: u64) -> u64 {
let mut prev_prev: u64 = 0;
let mut prev: u64 = 1;
if n == 0 {
return 0;
}
for _ in 2..=n {
let new_term = prev_prev + prev;
prev_prev = prev;
prev = new_term;
}
prev
}This type of code should be relatively clear to most people with programming experience: loop over integers, sum the two previous elements of the sequence to build the next one, update the program state for the next iteration. In the article I linked, they compare this to a tiramisù recipe given step by step.
Functional programming, on the other hand, is about describing the what. The idea here is that the step-by-step style of imperative programming can make it hard to actually understand what is happening. It takes a lot of cognitive effort to keep track of state throughout loop iterations, and even though the Fibonacci sequence is one of the simplest examples I can think of, this style doesn't even make the formula behind it clear at all. In functional programming, you mostly compose expressions and function calls instead of issuing statements that mutate state (don't hold me to this too much, it's an illustrative claim). The matching part of the tiramisù analogy here would be a composition diagram.

A functional version of the code above would make heavy use of recursion and would look like this:
fn functional_fibonacci(n: u64) -> u64 {
fn helper(n: u64, a: u64, b: u64) -> u64 {
match n {
0 => a,
_ => helper(n - 1, b, a + b),
}
}
helper(n, 0, 1)
}Recursion lets us write the definition down more directly: each term comes from the two previous ones.
The reason we use a helper function here is that a naive Fibonacci recursion would end with f(n - 1) + f(n - 2). Languages whose compilers implement tail-call optimization, like OCaml, Haskell and Gleam, can reuse the function frame instead of growing the stack when the function ends with a recursive call. The helper allows us to do just that.
Is that it?
The functional version really shows the sequence definition (which makes sense since it's a recursive sequence). In practice, functional programming also correlates with a few other aspects, although every language does it differently and none of these are unanimously found in all FP languages:
- Immutable data structures: in the imperative example, we used mutable variables to hold a changing state throughout a loop. In functional programming, data tends to be immutable. Instead, new data is built out of the input (of course, memory is often reused when possible). This can be a bit tough to get used to, but it's one of the best things you can do for the quality of your programs.
- Algebraic data types: this one might be more of a lineage thing (a lot of FP languages I'm familiar with are descended from ML). Algebraic data types are essentially union types which can hold data (to keep it super simple). Very useful, I find it hard to go back to a language without them.
- Monads and all that jazz: to keep it simple, monads are types that wrap other types and let you chain operations on the value inside, like
Option<T>orResult<T>in Rust (and all the cousins in the ML languages). See more in the box below. - Separation of side effects: because FP revolves so much around functions, a natural distinction arose between pure functions, which only depend on their input and have no side effects (think
x -> x + 2), and impure functions, which have side effects: they communicate with the external world, they can intermittently fail, etc. FP languages like to draw a clear distinction between the two, and many even do it at the signature level (Haskell has anIOmonad for this).
I'll be honest, I don't think you can really appreciate the difference between imperative and functional programming using something as basic as the Fibonacci sequence. I discovered that the poster child of FP is ‘quicksort’, an efficient list sorting algorithm. Let's see the difference between the two implementation styles using Rust and Gleam.
fn quicksort(xs: &mut [i32]) {
if xs.len() <= 1 {
return;
}
let pivot = xs[xs.len() - 1];
let mut i = 0;
for j in 0..xs.len() - 1 {
if xs[j] <= pivot {
xs.swap(i, j);
i += 1;
}
}
xs.swap(i, xs.len() - 1);
quicksort(&mut xs[..i]);
quicksort(&mut xs[i + 1..]);
}import gleam/list
fn quicksort(xs: List(Int)) -> List(Int) {
case xs {
[] -> []
[pivot, ..rest] -> {
let smaller = list.filter(rest, fn(x) { x < pivot })
let larger = list.filter(rest, fn(x) { x >= pivot })
list.flatten([quicksort(smaller), [pivot], quicksort(larger)])
}
}
}Both pieces of code achieve the same thing: they sort a list by selecting pivot values and sorting values above and below this pivot. This is a very straightforward recursive problem and it's no surprise it suits FP so well. As I mentioned before, the functional version is really good at describing the solution while the imperative version gets confusing by describing how to build it.
A lot of sources on FP tend to descend into a mathematical rabbit hole which can lose most readers, no matter how familiar they are with math. In my opinion, it's because a lot of these abstract concepts are way overkill for understanding how to use a language (language-building is another matter). In this little box, let me give you the super basic intro so you can read these descriptions without zoning out.
First of all, category theory is a way to represent relations between entities in a super fancy mathematical framework. All you need to know here is that you can describe types and morphisms (special functions) between those types as a category. Whenever you write a function signature, you define a domain (type of inputs) and a codomain (type of output). The function acts as a morphism in category theory.
From there, you can build more complex structure, the most famous of all being the monad. To keep it reaaaally simple, think of a type constructor (like Option or Result) as a box, and of three levels of operations over what is inside. In Rust, Option and Result are not types in and of themselves: they are mappings from types to new types T -> Result<T>.
- A functor lets you
mapover the box:map: (T -> U), M<T> -> M<U>. This is the one shared with list-like structures. - An applicative lets you
applya function that is itself in a box to a value in a box:apply: M<(T -> U)>, M<T> -> M<U>. - A monad lets you
bind:bind: M<T>, (T -> M<U>) -> M<U>. The function returns a new box, andbindflattens the two into one.
Some FP languages
The title of this post mentions a functional ladder, and the reason for this is that I intend to give you a little introduction to some FP languages I had the pleasure of getting to know, from more familiar to less familiar.
The ladder is not a strict ranking: it is the order I would walk someone through. Rust keeps the C-like syntax and adds FP as an option. Gleam keeps the C-like syntax but removes the imperative escape hatches. OCaml changes the syntax and makes FP the default, while still allowing mutation. Haskell changes the syntax and the way effects are tracked. A lot of the difficulty of FP languages comes from a syntax more adapted to their purpose (looking at you, Haskell), but the essence of what they do is contained in the previous section.
Rust
Rust will be our starting point here. It's not a pure FP language at all. Instead, it's an imperative language with a lot of FP inspiration. That makes it the perfect starting point to showcase some C-style syntax with FP concepts. I've already described Rust at length and it's a pretty mainstream language, so I won't reintroduce it here.
fn fibonacci(n: u64) -> u64 {
fn helper(n: u64, a: u64, b: u64) -> u64 {
match n {
0 => a,
_ => helper(n - 1, b, a + b),
}
}
helper(n, 0, 1)
}enum Color {
Red,
Blue,
Green,
}
enum Pet {
Cat(String),
Dog(String),
}
fn pet_name(pet: Pet) -> String {
match pet {
Pet::Cat(name) => name,
Pet::Dog(name) => name,
}
}// Rust has no Option::apply, so here is a small one
fn apply<A, B, F: Fn(A) -> B>(f: Option<F>, x: Option<A>) -> Option<B> {
f.zip(x).map(|(f, x)| f(x))
}
// Functor (map)
Some(5).map(|x| x + 1);
// Applicative (apply)
apply(Some(|x| x + 1), Some(5));
// Monad (bind)
Some(5).and_then(|x| Some(x + 1));This is the bottom rung of our ladder: you can use FP wherever you want within imperative-land, you get introduced to monads and chaining (via iterators) without really having to understand how they work. Perfect to dip your toes in.
Gleam
I could have chosen any of Erlang's cousins, but I really like Gleam and its syntax is still very C-like, very similar to Rust (much more than the other two). To keep it short, think of it as Rust but with immutable data only, no loops (only recursion), no if expressions (only pattern matching) and no traits (only functions).
fn fibonacci_loop(n, a, b) {
case n {
0 -> a
_ -> fibonacci_loop(n - 1, b, a + b)
}
}
fn fibonacci(n) {
fibonacci_loop(n, 0, 1)
}type Color {
Red
Blue
Green
}
type Pet {
Cat(name: String)
Dog(name: String)
}
fn pet_name(pet: Pet) {
case pet {
Cat(name) -> name
Dog(name) -> name
}
}import gleam/option
// Gleam has no option.apply, so here is a small one
fn apply(f, x) {
case f, x {
option.Some(fun), option.Some(value) -> option.Some(fun(value))
_, _ -> option.None
}
}
// Functor (map)
option.Some(5) |> option.map(fn(x) { x + 1 })
// Applicative (apply)
apply(option.Some(fn(x) { x + 1 }), option.Some(5))
// Monad (bind)
option.Some(5) |> option.then(fn(x) { option.Some(x + 1) })At this step, things get a bit harder. Gleam removes every imperative safety net you might have had in Rust. You don't have a choice: functions are all you can use for most of your control flow, and you need to accept immutability as a default. Yet the syntax is friendly, and Gleam was itself designed to be easy to learn, while BEAM, the Erlang VM powering it, brings a rich ecosystem for free.
OCaml
OCaml is a rather popular language in FP circles. It's what I would call the heir to the ML family as things stand. Having studied in France, I was naturally taught some OCaml at some point, and I remember back then thinking it felt a lot more like writing math than writing a program per se. OCaml is a big inspiration for Rust's functional side, and Rust's compiler was written in OCaml for quite a while. This means a lot of things that a Rustacean might be used to are naturally found in OCaml.
let fibonacci n =
let rec helper n a b =
match n with
| 0 -> a
| _ -> helper (n - 1) b (a + b)
in
helper n 0 1type color = Red | Blue | Green
type pet =
| Cat of string
| Dog of string
(* Pattern match on type *)
let pet_name = function
| Cat name -> name
| Dog name -> name(* OCaml has no Option.apply, so here is a small one *)
let apply f x =
match f, x with
| Some g, Some x -> Some (g x)
| _ -> None;;
(* Functor (map) *)
Option.map (fun x -> x + 1) (Some 5);;
(* Applicative (apply) *)
apply (Some (fun x -> x + 1)) (Some 5);;
(* Monad (bind) *)
Option.bind (Some 5) (fun x -> Some (x + 1));;We're already on the difficult part of the climb here. OCaml may bring back a few creature comforts (some mutability), but advanced FP concepts are at the forefront (e.g., functors). This is a good place to stop if you want to live in FP-land. I find it the perfect amount of theory and practical choices, and a very pleasant language.
Haskell
Haskell is the alien in this little group, and the one that feels the closest to writing true math. I can only recommend the absolutely amazing Learn You a Haskell guide if you'd like to learn the language: it's clear, well written and just the best reference out there.
Haskell has a lot of little quirks and features that make its syntax difficult at first, but in a way it may be the simplest of the languages in this whole list. Everything in Haskell is somehow a function or a value, and all the little specificities you learn in other languages tend to feel more unified there. I cannot do justice to the language or pretend to give an introduction here, so instead let's showcase the same code as for the others in Haskell, and I'll try to build some intuition later on.
fibonacci_loop :: Int -> Int -> Int -> Int
fibonacci_loop a _ 0 = a
fibonacci_loop a b n = fibonacci_loop b (a + b) (n - 1)
fibonacci :: Int -> Int
fibonacci n = fibonacci_loop 0 1 ndata Color = Red | Blue | Green
data Pet
= Cat String
| Dog String
pet_name :: Pet -> String
pet_name (Cat name) = name
pet_name (Dog name) = name-- Functor (map)
fmap (+ 1) (Just 5)
-- Applicative (apply)
Just (+ 1) <*> Just 5
-- Monad (bind)
Just 5 >>= (\x -> Just (x + 1))Yikes! I know, the monads block looks awful at first sight. The symbols are unfamiliar, but they are the same three operations as before: fmap/<$> is map, <*> is apply, and >>= is bind. I'll come back to this in the comparison below.
I think Haskell is the apex of FP (at least as far as I know) which is why it's the top of the ladder here. With Haskell, you really get all the benefits of FP: it's a lazy language (no evaluation unless necessary), so it's easy to compose functions, describe complex solutions (even infinite ones sometimes) and only do the necessary amount of work. Haskell is definitely a language that benefits from the theory behind FP: every syntax element, every data structure is built around the theoretical concepts we covered (functors, monads, etc.). To its credit, it brings all of this and still remains a productive language. You can build web servers, REST APIs and all that with Haskell as easily as you would in OCaml.
A little comparison
Okay, now we have a few code blocks to compare all the languages. Let's go through them side by side. Remember that these are only a short window into each of these very different programming languages. Let's start with a little summary diagram.
All of them have functions, closures1, algebraic data types, pattern matching, and option/result types. It's not so surprising: they all sort of belong to the same family (± for Haskell). Usually, the syntax is what really scares people immediately. Both Gleam and Rust are rather C-like, but OCaml and especially Haskell can really look weird if you're not used to it.
Rust starts showing its imperative roots when you consider things like type inference, tail-call optimization,2 and function piping/composition. For the latter, the trait-style methods of Rust allow some form of chaining, but there is no built-in piping operator like |> (in Gleam and OCaml) or composition . (in Haskell).
Immutability is another big difference. Rust and OCaml both have immutability as a default, but both allow mutation when needed (which isn't a bad thing for most cases tbh). In OCaml, you'd use it when you really have no choice, while in Rust it's an integral part of its style (not the preferred case, but definitely a necessity in systems programming). Technically, Haskell also allows mutation via certain side-effect monads but that's a bit advanced for this post.
Haskell, the top rung of the ladder, is once again where things get kicked into another gear. As a lazy-first language with type-encoded side effects and higher-kinded types, it makes you really dig into the theory part of FP and gives you access to a whole zoo of advanced features (most of which I don't really get yet).
The price of FP
Of course, everything good comes at a price, and FP is no different.
- Immutability is not free: nothing truly beats in-place mutation performance-wise (critical low-overhead systems are where you'd have no choice in Rust), even when the language does its best to reuse memory where it can.
- Laziness is really cool, and can help do a lot, but it also sometimes makes it really hard to keep track of what's happening and where things are executed.3
- OCaml and Haskell have more confusing tooling and a smaller ecosystem than Rust and to some extent Gleam (which basks in the Erlang ecosystem).
- Recursion-first approaches can be a bit risky. You really need the compiler to be on top of TCO if you don't want your whole program to crash unexpectedly, especially in Haskell, where it's easy to create infinite recursion.
Conclusion
This is only a small part of functional programming. A thorough treatment would have required more time and words than I can muster here. FP is a large domain, represented by a large swathe of languages (more than the four I showed here) and is the basis for some of the most important software used in the world (compilers, but also finance and research).
If you want to climb this ladder, I suggest dipping your toes with Rust's functional side. Then, why not spend a weekend playing with Gleam? The familiar syntax makes the transition rather smooth, and the BEAM ecosystem makes you productive really fast. If you're hungry for a bit more, OCaml is also a rather easy transition. It shares so much with Rust, and it was built to be versatile, so it's usually not that hard to get something done with it. I would only go with Haskell if the small tidbits of theory I mentioned here and there didn't scare you but instead made you curious. While you don't need a whole degree in category theory to use Haskell, there are a lot of things that just make more sense if you dig in the theory too.
References
If you are interested in learning more, these are the resources I keep coming back to:
- What's Functional Programming All About? by Li Haoyi. Amazing read, the first time I really understood what FP is all about.
- Mostly Adequate Guide to Functional Programming. This is a really good reference which uses JavaScript in case you're more familiar with that.
- Why Functional Programming Matters by John Hughes. A reference paper on FP itself, and its principles.
- The Gleam and OCaml language tours.
- Learn You a Haskell for Great Good! by Miran Lipovača. The friendliest way into Haskell, only for the brave.
- Category Theory for Programmers by Bartosz Milewski. Useful if you want to understand Haskell.
-
Anonymous functions which can capture surrounding variables. ↩︎
-
It's not that the Rust compiler doesn't do TCO, but it doesn't guarantee it, which can become a problem when you really want it. ↩︎
-
If you've worked a lot with Polars DataFrame vs LazyFrame, it's the same thing. LazyFrames are more efficient, but sometimes you need to inspect or make sure a computation is done at some specific point. ↩︎