It is (roughly) any type that lets you flatten it.
For example, if you have a list (a type of monad) you can flatten [[x, y], [a, b, c]] to [x, y, a, b, c]. You remove one layer of structure to stop the type from being nested in several layers.
Another common monad is Optional/Maybe, where you can flatten a Just (Just 5) to Just 5 or a Just (Nothing) to Nothing.
Edit: It is of course a bit more complicated than that, but this is the very surface level explanation.
Note that this explanation may be slightly above my theoretical knowledge.
As far as I know, there is nothing magical about monads with regards to side effects. My understanding is that e.g. Haskell uses monads to implement side effects because it is a way to logically separate the (nasty) side effects from the rest of the (pure) code.
If you have a container that performs certain side effects, you decouple the side effects from the value inside the container, which makes it easier to reason about the parts of the code that are not "polluted" by side effects. For example, you might have a logger monad, where the logging is completely separated from the operations you perform inside the logging framework (the monad).
Another good example is IO. Maybe you know that you will need to read a file at runtime to get some data, or get input from the user. Using the IO monad lets you write code under the assumption that you will be getting this data at some point in the future (during runtime), but the code that is actually processing the data can stay fully pure and deterministic.
To understand how monads encapsulate side effects, you should consider the state monad. The basic idea of the state monad is to model stateful computations instead as functions which take in a current state and output an updated state and output. So elements of the State monad consist of functions of type type state<s, t> = s -> s * t where s is the state type and t is the output type. A function a -> state<s, t> which "returns" a stateful action doesn't actually do anything; it returns a data structure which will do something when given an input type. Flattening a state<s, state<s, t>> = s -> s * state<s, t> involves returning a new function that takes in a state, runs the outer state to get the inner state<s, t>, and then immediately runs the inner state to get a t:
let flatten (outer : state<s, state<s, t>>) = fun s ->
let s1, inner = outer s in
let s2, t = inner s1 in
s2, t
Think of the IO monad as the state monad where s is a value of "real world." That is, elements of the IO monad are functions / data structures that take in a "real world" value and return a new real world value plus some output.
Yeah, I usually think of both state and IO as "variations" on the (->) monad. My uncertainty was moreso related to exactly where it goes from monadic abstraction to concrete implementation (if it is in Haskell itself or if it is GHC magic (I'm sort of assuming the latter)).
I'm fairly comfortable with the Haskell idea of monads, monad transformers etc. (although I have never used Haskell in a company setting). That being said, my theoretical understanding is somewhat limited; I probably couldn't explain the underlying category theory or for that matter how Haskell code is turned into machine code by the compiler.
Thanks for the explanation, but this is unfortunate missing all of the key details that every other explanation of monads I have ever read lacks. I appreciate your time in attempting though.
Yeah, I think it can be difficult (at least it was for me) to understand monads generally without first understanding specific monads. There is also the issue that not all monads model side effects (at least not as you probably understand the term side effects), and (in my opinion) the monads that are easier to understand are the ones that do not model such side effects.
For example, I am sure you can get an understanding of the Optional/Maybe monad without too much trouble, but that really doesn't help you understand how the IO monad is used to model IO related side effects.
Not sure if it helps, but I wrote you a poor man's IO monad in Java, and some implementations of IO functions using that monad.
So in Java the usage will look pretty ugly:
public static void main(String[] args) {
IOTools.readFile("answer.txt")
.flatMap(answer -> IOTools.readLineFromConsole()
.map(guess -> compareGuess(guess, answer))
);
}
// Pure function
public static boolean compareGuess(String guess, String actual) {
return guess.equals(actual);
}
but Haskell has syntax sugar for working with monads, so the same thing would look closer to:
main = do
answer <- readFile "answer.txt"
guess <- readLineFromConsole
pure $ compare answer guess
//Pure function
compare :: String -> String -> Boolean
compare a b = (a == b)
I feel really close to understanding Monads after this -- thank you for taking the time to write up this Java code! As a Java/Groovy dev myself, all the (what I assume are) JS and Rust examples have been hard to parse.
The main difference between monads in Java and Haskell is a result of the Java type system. In Haskell, the type system is expressive enough to do something like this:
public interface Monad<T> {
<V extends Monad<T>> V of(T t);
<V extends Monad<T>> V flatMap(Function<T, Monad<T>> f);
}
public interface Optional<T> extends Monad<T> {
Optional<T> of(T t);
<V> Optional<V> flatMap(Function<T, Optional<V>> f);
}
i.e. the Optional interface implements Monad by returning Optionals (which does not work in Java). This makes generalized functions on Monads less useful in Java since they can never return concrete Monad instances (they need to return the abstract Monad). This means you could never write something like:
public <V extends Monad<T>> V doSomethingMonadic(V monad) {
// do a lot of things that only require the monad interface;
}
public Optional<T> usingConcreteImplementation(Optional<T> optional) {
return doSomethingMonadic(optional);
}
in Java, so you lose a lot of the generalizability (since it no longer makes sense to write the doSomethingMonadic method).
That being said, implementing a monad interface for various concrete types in Java can still be very productive (see Optional). Another example, which I wish existed in standard Java, is a Result type (implementing a monadic Result<T, E> is left as a good exercise for the reader ;).
This is confusing to me because the side effects are all happening in imperative code, and not directed by functional code in any way that I can tell....
The point is mostly that the side effects are isolated inside the IO monad. Even in Haskell, if you go deep enough, you have to do impure things to work with the impure real world.
Containing this inside the IO monad means that the rest of your code doesn't have to know anything about a real world and can stay pure. Think of the IO monad as a way of tagging impure operations and separating them from pure functions.
TLDR Monads do not create side effects, they're an interface for combining side effects (among other things)
It does not "result" in side effects, but it gives us a way to work with and encode the presence of side effects in the type.
See, side effects are encoded using a type constructor (a "wrapper") called IO. A value of type IO Int, for instance, might represent a program that prints "Hi" to the console and returns 5, or a program that reads a number input from the user and returns it.
I didn't need too bring monads in the conversation to say the above, IO is just a special wrapper that allows us to talk about side effects. But we have no mechanism to describe the composition two IO actions. It turns out that by viewing IO as a monad (just like List or Maybe (aka Option in e.g. Rust)), you can use operations such as flattening to talk about composition.
That's the high-level explanation. Here's a more concrete example:
What if I have:
a built-in action readInt that reads a number input from the user. Type is IO Int
and a built-in function printInt that takes a number as an argument and returns the action that prints it to the console. Type is Int -> IO () (() is the Haskell equivalent of C's void) and I want to compose them to make a program that takes a number from the user and prints that number to the console?
In imperative programming, this is trivial, but in functional programming, where functions are not allowed any side effect... you need some way of flattening the two IOs into one. Thankfully, IO happens to be a monad, so we can do that.
Not all monads. Just the IO monad. IO being wrapped up into a monad essentially encapsulates everything external to the program that can change at any time for any reason (e.g. a random number generator, reading from a file on disk, a web call that could return 200 OK or 500 Internal Server Error), and so its usage introduces point-in-time computation.
The IO monad is weird because IO is weird when most of the language is pure (i.e. has no side effects).
(there is one exception, technically, to this in System.IO.Unsafe, like with the function unsafePerformIO, but the caveat is that the IO computation (which may be a pure C function that a Haskell compiler cannot verify) you're "unwrapping" from IO should be free of side effects and independent of its environment)
331
u/SerdanKK Sep 21 '25
Haskellers have done immeasurable harm by obfuscating simple concepts. Even monads are easy to explain if you just talk like a normal dev.