I am learning Haskell and trying to understand Monads. I have two questions:
From what I understand, Monad is just another typeclass that declares ways to i
There are three main observations concerning the IO monad:
1) You can't get values out of it. Other types like Maybe
might allow to extract values, but neither the monad class interface itself nor the IO
data type allow it.
2) "Inside" IO
is not only the real value but also that "RealWorld" thing. This dummy value is used to enforce the chaining of actions by the type system: If you have two independent calculations, the use of >>=
makes the second calculation dependent on the first.
3) Assume a non-deterministic thing like random :: () -> Int
, which isn't allowed in Haskell. If you change the signature to random :: Blubb -> (Blubb, Int)
, it is allowed, if you make sure that nobody ever can use a Blubb
twice: Because in that case all inputs are "different", it is no problem that the outputs are different as well.
Now we can use the fact 1): Nobody can get something out of IO
, so we can use the RealWord
dummy hidden in IO
to serve as a Blubb
. There is only one IO
in the whole application (the one we get from main
), and it takes care of proper sequentiation, as we have seen in 2). Problem solved.