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?
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; }
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.
Pure functions should not use or refer to global variables, static variables, or variables outside its function scope.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With