Examples of pure and impure functions
To illustrate the difference between pure and impure functions, let's look at some examples in different languages. In JavaScript, a pure function could be something like this:
function add(x, y) {
return x + y;
}
This function has no side effects and is referentially transparent, because it only returns the sum of its arguments and does not modify or depend on anything else. An impure function could be something like this:
let counter = 0;
function increment() {
counter++;
return counter;
}
This function has a side effect and is not referentially transparent, because it modifies and depends on a global variable counter, and returns different values depending on how many times it is called. In Python, a pure function could be something like this:
def square(x):
return x ** 2
This function has no side effects and is referentially transparent, because it only returns the square of its argument and does not modify or depend on anything else. An impure function could be something like this:
def print_hello():
print("Hello")
return None
This function has a side effect and is not referentially transparent, because it prints to the standard output and does not return anything meaningful. In Haskell, a pure function could be something like this:
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)
This function has no side effects and is referentially transparent, because it only returns the factorial of its argument and does not modify or depend on anything else. An impure function could be something like this:
getLine :: IO String
getLine = do
c <- getChar
if c == '\n'
then return ""
else do
cs <- getLine
return (c:cs)
This function has a side effect and is not referentially transparent, because it reads a line from the standard input and returns an IO action, which is a special type that represents an interaction with the outside world.