Side effects

Table of Contents

Side effects

From Real World Haskell…

A side effect introduces a dependency between the global state of the system and the behaviour of a function.

For example, let’s step away from Haskell for a moment and think about an imperative programming language. Consider a function that reads and returns the value of a global variable. If some other code can modify that global variable, then the result of a particular application of our function depends on the current value of the global variable. The function has a side effect, even though it never modifies the variable itself.

Side effects are essentially invisible inputs to, or outputs from, functions. In Haskell, the default is for functions to not have side effects: the result of a function depends only on the inputs that we explicitly provide. We call these functions pure; functions with side effects are impure.

If a function has side effects, we can tell by reading its type signature: the type of the function’s result will begin with IO.

ghci> :type readFile
readFile :: FilePath -> IO String

Links to this note