Functional Programming utilizes functions to create programs and focuses on separating pure functions from impure functions.
The following table that shows a comparison of pure and impure functions is licensed under CC BY-SA 4.0:
- Original Credit: Sam Halliday - "Functional Programming for Mortals with Scalaz"
- License: legal code & legal deed
- Changes made
- Converted idea into a table that compares pure functions with impure functions
- Further expand on "does it interact with the real world" idea with more examples from the original work
Pure functions have 3 properties, but the third (marked with
*) is expanded to show its full weight:
|Pure||Pure Example||Impure||Impure Example|
|Given an input, will it always return some output?||Always |
|Given the same input, will it always return the same output?||Always |
|*Does it interact with the real world?||Never||Sometimes|
|*Does it access or modify program state||Never|
Original list is copied but never modified
|*Does it throw exceptions?||Never||Sometimes|
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 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.