Can a pure function depend on an external constant?

The article I read provides this as an example of an impure function (in JavaScript):

const tipPercentage = 0.15; const calculateTip = cost => cost * tipPercentage; 

This seemed like a slightly strange example to me, since tipPercentage is a constant with an immutable value. General examples of pure functions allow dependence on immutable constants when these constants are functions.

 const mul = (x, y) => x * y const calculateTip = (cost, tipPercentage) => mul(cost, tipPercentage); 

In the example above, correct me, if I am mistaken, calculateTip usually classified as a pure function.

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

+5
source share
1 answer

Yes, this is a pure function. Pure functions are referentially transparent , that is, you can replace the function call with your result without changing the behavior of the program.

In your example, it is always valid for replacement, for example. calculateTip (100) anywhere in your program with a result of 15 without any changes in behavior, so the function is clean.

+4
source

Source: https://habr.com/ru/post/1270850/


All Articles