[Haskell-cafe] A Question about IO monad

Nikita Karetnikov nikita at karetnikov.org
Sun Mar 1 11:58:17 UTC 2015

> You can indeed write "Maybe a -> a" function easy, because you have Maybe
> constructors exported for you. But please note that this will lead to
> non-total function, e.g. it will have to return an error in case of call
> with Nothing, so you should avoid writing and using functions like this.

A tiny nitpick: you can get a total function if you return a default
value instead of erroring out.

>> Sometimes IO do something and return something, i wonder if the return
>> type, for example is IO Int means it will return an int, could i purely
>> fetch the int?

The IO in IO Int means that instead of just returning an Int, a
computation may produce a side-effect (like writing a string to standard
output).  Since reasoning about code without side-effects is much
simpler, you want to separate it from impure code.  That's what IO is
for.  Once you're inside IO, you're dealing with impure code, so you
want to keep track of things that rely on it.  You can't* and don't want
to escape.

* As Konstantine points out, there are legitimate cases for using
  unsafePerformIO, like writing an FFI binding to a pure function.
  Haskell type system can't see whether the function in question is pure
  or not, so it's tagged with IO.  However, if you know that it's pure,
  you can explicitly state that by using unsafePerformIO.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 818 bytes
Desc: not available
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20150301/72356cf0/attachment.sig>

More information about the Haskell-Cafe mailing list