Hacker News new | ask | show | jobs
by codeflo 2390 days ago
The way most people explain this is completely backwards. Monads don't actually solve the I/O problem. So forget about monads and just consider how to mathematically model I/O.

Take something like getStrLn (which reads a line from STDIN). What is "getStrLn", as a mathematical object? It's not a string, rather, it's some kind of "I/O operation" that when executed, returns a string. Haskell calls such an object an "IO String". Similarly, the expression (putStrLn "foo") is an I/O operation that when executed, doesn't return anything. Haskell calls this an "IO ()".

Once you develop an intuition of I/O operations, you can see how you might want to combine atomic I/O operations into larger and larger I/O operation, feeding the output from one as input into the other. Or how you could treat a plain Int as an "empty" I/O operation that when executed, simply returns the Int. And how your entire program, its "main" entry point, can be modeled simply as one large I/O operation.

You can do all of that, and write every possible kind of I/O code in Haskell, without ever learning about monads.

What are monads for, then? They generalize the structure of this approach, with its (>>=) and return operators, and apply it to other cases that don't have anything to do with I/O. But this step is completely optional! This is very similar to how the idea of a mathematical "field" generalizes the arithmetic operators (+, -, *, /) and applies them to objects that don't look anything like the rational numbers. You don't have to learn about fields to successfully use rational numbers. And we would never dream of explaining the abstract idea of fields to people before we introduce them to rational numbers. Yet almost every I/O tutorial in Haskell begins with a half-baked explanation of monads.

2 comments

That is how I finally got it, because I knew what groups/rings/fields were but did not realize at first that monads were just another abstraction like those and not an ontologically fundamental category. The way monads are usually presented leads you to believe that there is something magical in those axioms that somehow makes the impossible happen.
Learn the concrete, then abstract? That's sound wisdom about teaching most anything, in my opinion.