Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monadic impurity and Haskell's purity. How they are combined?

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.

like image 555
Dragno Avatar asked Jan 10 '13 10:01

Dragno


Video Answer


2 Answers

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?

like image 182
Ingo Avatar answered Nov 05 '22 13:11

Ingo


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.

like image 44
Hui Zheng Avatar answered Nov 05 '22 13:11

Hui Zheng