Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 210
samfrances Avatar asked Aug 14 '17 10:08

samfrances


People also ask

What makes a function pure?

A pure function is a function without any side effects. Consider the JavaScript code below: function updateMyName(newName) { const myNames = ["Oluwatobi", "Sofela"]; myNames[myNames. length] = newName; return myNames; }

Can pure functions use global variables?

Pure functions cannot use global variables, end of discussion. updateUserName : This one is impure because it has a big side effect: it's modifying the object it receives as a parameter. In JavaScript, objects are passed as reference, so any change you make on them inside the function will affect the original one.

Should pure functions be static?

Pure functions should not use or refer to global variables, static variables, or variables outside its function scope.


1 Answers

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.

like image 175
TheInnerLight Avatar answered Oct 28 '22 04:10

TheInnerLight