11 points · by david90 · 10y ago · 14 comments
> function sum(a, b) { return a + b }
> and this example is NOT
> const k = 2
> function addK(a) { return a + k }
This is wrong. Assuming the variable `k` is properly constant (never changes), `addK` is still a pure function.
The author seems to have gotten confused because they are working from an incorrect definition of what "purity" means.
This is language-specific for Javascript.
> It's not wrong in general.
It's not wrong in general, but it's also not right in general. The pattern is completely orthogonal to purity. Whether a closure is pure depends on a lot of factors, like the types of things in the closure and the functions it calls.
I said that in the context of the article obviously, which is about JS.
Might I suggest looking into a subsets of JavaScript where purity is decidable? It seems like the author is intuiting that purity is decidable for some nontrivial subset of JS (this is my intuition as well).
I think that we can determine cost variables assigned to a primitive value to be pure. From there we can build up that const functions which only contain pure expressions are pure. Note that this does not include fields on objects of any kind: a.b and a[b] are not necessarily pure even if both a and b are. In this way, I think we can determine that a subset of JS is pure. We can't, however, prove that any subset is not pure. Nevertheless, even proving a small subset to be pure might have implications for optimization.
> Relaxing the rules and allowing accessing other pure functions or constant values is fine, as long as the function is still consistent.
> trying to prove that the output changes is the same as trying to prove that the program finishes writing. Thus it is theoretically undecidable.