How does the monad construct help to maintain purity (in Haskell) while at the same time doing impure things? When for example you give print "Hello"
are you executing pure or impure code? It is a very subtle detail but something that helps better understand the idea of purity and impurity in functional languages.
The expression
print "Hello"
is indeed pure. As it doesn't print anything, but rather constructs something that, when executed, prints "Hello".
Here is an analogy:
A monk writes on a sheet of paper:
Go to a bordell and do filthy things with the prostitutes there.
Can we accuse the monk because of adultery, just because he wrote an instruction to engage in adultery?
The question in stackoverflow may answer your question: In what sense is the IO Monad pure?
In short, monad itself is pure, but it can issue impure instructions. To be a little bit more specific, monads can be viewed as a series of composable computation descriptions. Some of these computations may be dirty(i.e. have side-effect), but description itself is totally pure and clean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With