[Haskell-cafe] What are side effects in Haskell?
jake at pikewerks.com
Sat Dec 27 12:54:40 EST 2008
Hans van Thiel wrote:
> However, some functions in Haskell may have side effects, like printing
> something on the screen, updating a database, or producing a random
> number. These functions are called 'actions' in Haskell.
Not really true (disregarding things like unsafePerformIO). I haven't
been following this thread, so I don't know if anybody else has
suggested this, but perhaps it would be helpful to distinguish between
evaluating expressions and performing actions.
Evaluation is simply graph reduction, which is Haskell's only method of
computation. There are no side-effects when you evaluate an expression
(again, disregarding unsafePerformIO and company), even if that
expression evaluates to an IO action.
To perform an action is to cause the side-effect which that action
represents. *You* never perform an action in Haskell. The runtime does.
All you do is say how to evaluate those actions.
Essentially, what the IO monad does is give you a DSL for constructing
(by evaluation) effectful, imperative programs at runtime. The runtime
will cause your program to evaluate the next action, then perform it,
then cause your program to evaluate the next action, then perform it,
and so on. At no point is the purity of your program broken by this.
> However, there is a mechanism (sometimes) to compose functions using an
> extra type m a, m b, m c etc. instead of types a, b, c... This does not
> solve the problem concerning side effects, but it does provide a sort of
> 'Chinese boxes' to contain them within these type constructors m.
> Moreover, in the case of the type designation 'IO ...', you can't get
> anything out of the box. So now, at least, you've got a clean interface
> between the parts of your program which do not involve side effects, and
> the 'actions'.
This is another way to think of it. It is how I first thought of IO
before I discovered the way I described above. It's a pretty good
metaphor, and I don't think it's harmful, so you can stick with it for
now if you would prefer.
> If I guess correctly, then the general statement 'monads are for
> actions' is wrong. It should be something like, 'monadic composition is
> a useful method of generalization, which, by the way, allows you to
> isolate side effects in a controlled manner'.
Right on. Monads are extremely useful for things that don't involve
Hope this helps,
More information about the Haskell-Cafe