3 ms·
One advantage of monads is that they can communicate via the type that a function is not pure. I remember a serious bug in a trading system (distributed over mu
by grumpyprole 5y ago
One advantage of monads is that they can communicate via the type that a function is not pure. I remember a serious bug in a trading system (distributed over multiple time zones), that was caused by Java's toString reading the system locale from the OS. In Haskell, such a function would have a type that makes it clear the function is not pure, e.g. toString : Date -> IO String.
Monads are not the only way of tracking effects in the type, but they are one way. For example, Java has "checked exceptions", which also represent an effect in the type system.
Monads also allow one to assemble a computational ready for execution later. One can therefore write an Async library, without needing baked-in language support.
- cryptonector 5y agoNote that using a monad does not imply the code is impure. Using the IO monad does.
- grumpyprole 5y agoYes and some would argue that all Haskell functions are pure even those that return computations in the IO monad. One can use referential transparency to reason about the IO monad values also.
- cryptonector 5y agoSure, you can treat I/O functions as World -> World functions, but unlike other pure functions, the compiler can't compute them at compile time when they are applied to constant inputs. A program consisting entirely of pure function applications to constants can be evaluated at compile-time to just the constant(s) it would output, while a program that calls I/O functions cannot be (assuming those calls to I/O functions are not dead code).