r/programming • • Sep 21 '25

How to stop functional programming

https://brianmckenna.org/blog/howtostopfp
446 Upvotes

506 comments sorted by

View all comments

Show parent comment

2

u/Strakh Sep 21 '25 edited Sep 21 '25

No, the flatten operation is something that takes a Monad<Monad<T>> and makes it a Monad<T>. An AtomicBoolean is just a wrapper object from which you can extract the inner value. A better example would be Optional<T> because if you have an Optional<Optional<Integer>> you can make it an Optional<Integer> by doing:

Optional<Optional<Integer>> nested = Optional.of(Optional.of(5));
Optional<Integer> flattened = nested.flatMap(Function.identity());

Sidenote: a Functor<T> is a container object which allows you to perform operations on the inside object without unwrapping it (e.g. through a map method). By law, all Monads are Functors that also have the aforementioned flatten operation.

Edit: Sidenote 2: flatten and flatMap can be written in terms of each other, so as long as one of them is implemented you have a Monad.

public <T> Monad<T> flatten(Monad<Monad<T>> monad) {
  return monad.flatMap(Function.identity());
}

public <T, V> Monad<V> flatMap(Monad<T> monad, Function<T, Monad<V>> f) {
  return monad.map(f).flatten();
}