Functions, Closures and Monads
What's the difference between a function, a closure and a monad? It's not a joke, it's a TLDR note.

Functions
A function is a reusable piece of code that takes in parameters and returns a value - it also usually has an explicit name. They only consume what's passed in. A pure function is one which doesn't mutate state and produces deterministic output.
- Java
- TypeScript
- Rust
public int add(int a, int b) {
return a + b;
}
function add(a: number, b: number): number {
return a + b;
}
fn add(a: i32, b: i32) -> i32 {
a + b
}
Closures
An anonymous function which can access or "captures" variables from it's surrounding environment or scope. In Java we also have lambdas which are like closures, but can only capture variables from enclosing scope that are final or effectively final. In Rust, closures can capture variables by reference, mutable reference, or by value.
- Java
- TypeScript
- Rust
int x = 10;
Function<Integer, Integer> addX = (y) -> x + y;
let x = 10;
const addX = (y: number) => x + y;
let x = 10;
let add_x = |y| x + y;
Monads
A monad is more of a concept or a pattern that allows for chained computation with context. The context allows us to handle things like errors, optional values and async computation.
- Java
- TypeScript
- Rust
Optional.of(10)
.flatMap(x -> Optional.of(x + 1));
// Array is a Monad
[10].flatMap(x => [x + 1]);
Some(10)
.and_then(|x| Some(x + 1));
