News for hackers. Stuff that matters.
Re:Monads are a class of hard drugs by kmeisthax on Monday July 11, 2022 @11:33AM (#32057481)
The reason why most programmers struggle to understand Monads is that they are a tool for fixing several problems that don't exist in imperative languages. In functional languages, the order of operations does not matter, because the operations do not have side effects. Monads hack around this by forcing functions to be applied in a specific order and allowing them to store the side effects in the type.

For this same reason, my favorite explanation of monads is actually https://journal.stuffwithstuff.com/2015/02/01/what-color-is-...

Why? Because it does not explain monads at all. In fact, it does not even have the word "monad" in it. But the whole mess about "function coloring" brought up to describe async code is basically the same thing as the "mixing crack and heroin" problem in the original post here - at least in terms of developer experience. JavaScript has two built-in, uncustomizable monads: imperative and async; with the async monad being a superset of imperative but being harder to call and manage.

Rust has at least four: normal imperative code, Option, Result, and Future. We can't really talk about Monad<T> as a type in Rust because its trait system lacks higher-kindedness; so no monad transformers or colorless functions. But they all have combinators that let you sequence functions and store state away in the type. Option/Result let us hack exceptions into a language that does not have exceptions[0], and Future lets us hack user-mode/green threads into a language that is committed to OS stacks.

All the monad tutorials fail because they try to walk you through the underlying math that makes monads work in a functional language. This is wrong; nobody needs to understand the category theory behind the curtain even if it seems super-cool. It's just a hack to force ordering and state into a language that does not have it.

[0] panic!() does not count as an exception mechanism, even though it can be implemented with stack unwinding. There are panics that don't unwind (stack overflow) and you can compile programs that terminate-on-panic instead of unwinding.

Re:Monads are a class of hard drugs by sudosysgen on Monday July 11, 2022 @09:28PM (#32064477)
Fun fact though, you can actually implement a Monad type in C++. There's not really any reason to do so, but you can.