Pure vs Impure Functions

Visual Overview

Pure and Impure Functions

Functional Programming utilizes functions to create programs and focuses on separating pure functions from impure functions.

General Overview

Properties


The following table that shows a comparison of pure and impure functions is licensed under CC BY-SA 4.0:

Pure functions have 3 properties, but the third (marked with *) is expanded to show its full weight:

PurePure ExampleImpureImpure Example
Given an input, will it always return some output?Always
(Total Functions)
n + mSometimes
(Partial Functions)
4 / 0 == undefined
Given the same input, will it always return the same output?Always
(Deterministic Functions)
1 + 1 always equals 2Sometimes
(Non-Deterministic Functions)
random.nextInt()
*Does it interact with the real world?NeverSometimesfile.getText()
*Does it access or modify program stateNevernewList = oldList.removeElemAt(0)
Original list is copied but never modified
Sometimesx++
variable x is incremented by one.
*Does it throw exceptions?NeverSometimesfunction (e) { throw Exception("error") }

In many OO languages, pure and impure code are mixed everywhere, making it hard to understand what a function does without examining its body. In FP languages, pure and impure code are separated cleanly, making it easier to understand what the code does without looking at its implementation.

Programs written in an FP language usually have just one entry point via the main function. Main is an impure function that calls pure code.

Sometimes, FP programmers will still write impure code, but they will restrict the impure code to a small local scope to prevent any of its impurity from leaking. For example, sorting an array's contents by reusing the original array rather than copying its contents into a new array. Again, impure code is not being completely thrown out; rather, it is being clearly distinguished from pure code, so that one can understand the code faster and more easily.