samfrances
samfrances

Reputation: 3685

Can a pure function depend on an external constant?

An article I was reading gives this as an example of an impure function (in JavaScript):

const tipPercentage = 0.15;

const calculateTip = cost => cost * tipPercentage;

That struck me as a bit of an odd example, since tipPercentage is a constant with an immutable value. Common examples of pure functions allow dependence on immutable constants when those constants are functions.

const mul = (x, y) => x * y

const calculateTip = (cost, tipPercentage) => mul(cost, tipPercentage);

In the above example, correct me if I'm wrong, calculateTip would usually be categorised as a pure function.

So, my question is: In functional programming, is a function still considered pure if it relies on an externally defined constant with an immutable value, when that value is not a function?

Upvotes: 16

Views: 2259

Answers (2)

sepehr
sepehr

Reputation: 18445

Yes, theoretically, a function that abides by these two rules:

  • not causing side effects
  • not depending on "any mutable state"

can be considered pure, and as @TheInnerLight has put it well, provides referential transparency among other benefits. That makes the function in your example pure.

However, as the question is about & tagged with javascript, it is important to note that a function that depends on a const defined in the outer scope cannot always be considered pure:

const state = {}

function readState (key) {
  return state[key]
}

// A hypothetical setState() can mutate `state` and 
// therefore change the outcome of `readState` calls.

That is obviously because state value is not immutable (only the assignment is).

The rule of thumb is to prefer local over global when it comes to scopes. That provides better isolation, debuggability, and less cognitive load for the next reader.

Upvotes: 0

TheInnerLight
TheInnerLight

Reputation: 12184

Yes, it is a pure function. Pure functions are referentially transparent, i.e. one can replace the function call with its result without changing the behaviour of the program.

In your example, it is always valid to replace e.g. calculateTip (100) anywhere in your program with its result of 15 without any change in behaviour, hence the function is pure.

Upvotes: 14

Related Questions