Search code examples
haskellfunctional-programmingmonadspurely-functional

How Monads are considered pure?


I am very much new to Haskell, and really impressed by the language's "architecture", but it still bothers me how monads can be pure.

As you have any sequence of instructions, it makes it an impure function, especially functions with I/O wouldn't be pure from any point of view.

Is it because Haskell assumes, like all pure functions, that IO function has a return value too, but in form of opcode or something? I am really confused.


Solution

  • One way to think of this is that a value of type IO a is a "recipe", containing a list of instructions that if performed would have side effects. Constructing that "recipe" though, does not have any side effects. So a haskell program (whose type is IO ()) is basically a computation that constructs such a recipe. Importantly, the program does not execute any of the instructions in the recipe. When the recipe is completed the program terminates. Then the compiler (or interpreter) takes that recipe and executes it. But the code that the programmer wrote is not running anymore, so the instructions in the recipe are executed outside the scope of the program.