Is a nested pure function still a pure function?
functional-programming, immutability, javascript
Solution
External state is different from external code. If pure functions couldn't use external code, then there pretty much would be no such thing as a pure function at all. Even if all your function does is `x * 2`, in (many) pure functional languages even `*` is a function. So even this simple function cannot avoid calling other functions.
Function definitions are more or less just syntax details. You could inline the function body of external functions into a longer expression. E.g.:
function foo(a, b) {
return bar(a) + bar(b);
}
function bar(x) {
return x * 2;
}
is identical to:
function foo(a, b) {
return a * 2 + b * 2;
}
The only difference is reusability of code snippets and/or readability and maintainability. Not purity.
A function is pure if it doesn't cause side effects or is influenced by side effects/state outside itself. It stays pure as long as all the code it calls also conforms to that rule.
Problem
By definition, a Pure Function is pure if: - Given the same input, will always return the same output. - Produces no side effects. - Relies on no external state. So this is a pure function: ``` function foo(x) { return x * 2; } foo(1) // 2 foo(2) // 4 foo(3) // 6 ``` And this would be a pure function as well (in JavaScript context) ``` Math.floor(x); Math.floor(1.1); // 1 Math.floor(1.2); // 1 Math.floor(2.2); // 2 ``` The question: if we combine these 2 pure function, would it still be considered as a pure function? ``` // Nested with Math library function bar(x) { return Math.floor(x); } // Nested even deeper function foobar(x) { return foo(Math.floor(x)); } ``` Obviously, it still always return the same output given the same input without side effects, but does calling a function from other context (scope) break the law for "Relies on no external state"?