[Haskell-beginners] clarification on IO
Thomas Davie
tom.davie at gmail.com
Sat Feb 28 14:40:46 EST 2009
On 28 Feb 2009, at 10:13, Chaddaï Fouché wrote:
> On Sat, Feb 28, 2009 at 3:50 AM, Michael Easter
> <codetojoy at gmail.com> wrote:
>> Q1: The web page mentions that normal Haskell functions cannot cause
>> side-effects, yet later talks about
>> side-effects with putStrLn. I assume the key point here that IO
>> actions are,
>> by definition, _not_ normal functions?
>
> putStrLn is a perfectly pure function (there is no other kind in
> Haskell), it takes a String and return a value of type IO (), this
> value is like any other first class object in Haskell and can be
> manipulated as thus, the only difference is that this value can be
> computed in the context of the IO monad and then have a side-effect.
> The value of type IO a are often called actions but they aren't
> fundamentally different from other values.
Note, take this information with a pretty gigantic grain of salt. It
is true that you are writing a pure program when using IO functions,
but you should probably think about what that means.
The advantage of pure programs is that you get certain neat benefits
like not having to bother about "am I doing this in the right order"
or "will the system do weird random shit while this function is
executed". This is not true about IO typed functions. An IO typed
function generates an IO value which the runtime runs. That means,
that they essentially get us no further forward than C. In C we write
pure functions called C preprocessor macros. These pure functions
generate imperative programs (C programs) which are run by the runtime
(the C compiler and your OS). This is no different to IO.
So, the lesson – IO is in theory pure. But that doesn't mean that we
get all the nice benefits of functional programming while using the IO
monad. One can say pretty much the same thing about all stateful
monads, although IO is by far the worse, in that the state can be
influenced by chunks of reality totally outside your control.
Bob
More information about the Beginners
mailing list