# [Haskell-beginners] "pure" versus "impure" code

Paul Sargent psarge at gmail.com
Fri May 20 17:07:24 CEST 2011

```On 19 May 2011, at 21:12, Costello, Roger L. wrote:

> My understanding is that:
>
> - Pure code is code that does no I/O
>
> - Impure code is code that does I/O

I don't particularly like that definition. It's true, but the definition of I/O has to be very board.

The definition I use is that a pure function is one that
- takes input only from it's parameters.
- outputs only via it's return value.

If x is an external variable in memory
Pure  : f(b,c) = b + c
Impure: f(b)   = b + x;         (violates first  rule - Uses value in x)
Impure: f(b,c) = 1 ; x = b + c; (violates second rule - Changes value in x)

Pure functions can combine to make larger pure functions. Impure functions combined with pure functions make larger impure functions.

> Also, it is my understanding that good software design is to isolate/separate the impure code from the pure code. Is that correct?

As the result of pure code is dependent only on it's inputs you can make statements like:
f(1,2) is always is equal to f(1,2) at any time

...without knowing what function f() is. That's quite powerful, and can be useful in optimisation.

Another way of phrasing it - A pure piece of code causes no side-effects, and it is not effected by other code's side-effects. This property is very useful in parallel computations.

Separating pure code out can be useful, but most programs in most languages don't. That's mainly due to the use of shared state variables between functions. Object orientation is inherently impure as every object has retained state, modified and used by the methods. This isn't necessarily a bad thing. At some point all programs have to be impure otherwise they'll always calculate the same result.

> Does that principle apply to all programming languages, or just Haskell?

Yes, it applies to all languages.

```