Comp 110 Pure vs. Impure Functions

Pure vs. Impure Functions

Pure functions are functions that contain all of the tools needed to solve a problem within its definition. In other words, using only the parameters passed to the function as arguments, it can get the job done.

Impure functions, however, involve some external state not accounted for by the parameters. For example a function that depends on some user input, global variable or object's properties would be considered impure as it cannot stand alone in a program. Impure functions rely on code implemented outside of itself to work properly.

Let's take a look at the differences between these two types of functions with some examples.

1. The sum of two numbers

let sum1 = (n: number, m: number): number => {            
    return n + m;
};
let x: number = await promptNumber("Choose a number?");
let sum2 = (n: number): number => {            
    return x + n;
};

In this case the first sum function is pure, but the second one is impure because it depends on the user's input for x.

2. Modifying an Object

Class Point {            
    x: number;           
    y: number;
} 
let printPoint = (p: Point): void => {            
    print(p.x + ", " + p.y);
};
Class Point {            
    x: number;            
    y: number;    
           
    printPoint = (): void => {                       
        print(this.x + ", " + this.y);            
    }
}

This example highlights not only the difference between pure vs. impure functions but also functions vs. methods.

Methods are just a special type of function that belong to a class. In this case, the printPoint function at the top is pure. It takes in a Point object as a parameter and prints output to the screen based off its properties.

The printPoint method is impure as its functionality depends on the state of the specific Point object that it is called on. For a review on the this keyword, click here.