How to get rid of IO
I have something of type
IO a, but I need something of type
How can I get that?
You can get rid of it, but you almost certainly don't need to. The special safety belt of Haskell is that you cannot get rid of IO! Nonetheless, the biggest parts of Haskell programs are and should be non-IO functions. Applications using both IO and non-IO functions are written by plugging together these two flavors of functions using functions like
(>>=). These functions allow useful IO while having all the safety properties of a pure functional programming language.
You can hide some functions using do notation, which looks like this:
do text <- readFile "foo" writeFile "bar" (someComplicatedNonIOOperation text)
Without hiding the functions, this would look like:
writeFile "bar" . someComplicatedNonIOOperation =<< readFile "foo"
What we didn't tell you at the beginning
There is a function which directly answers the initial question, namely,
It is however not intended for conveniently getting rid of the
It must only be used to wrap IO functions that behave like non-IO functions,
Since this property cannot be checked by the compiler, it is your task and thus the
unsafe part of the name.
(Some library writers have abused that name component for partial functions. Don't get confused!)
You will only need this in rare cases and only experienced programmers shall do this.
- Introduction to IO
- Avoiding IO - Avoiding IO in the first place is a good thing, and we tell you how to achieve that
- Tackling the awkward squad