r/javascript • u/vinnl • Aug 27 '16
Is your JavaScript function actually pure?
http://staltz.com/is-your-javascript-function-actually-pure.html12
u/memeship Aug 27 '16
• The elements in the array don’t have their valueOf functions tampered with
This possibility means literally nothing in JS is pure.
Also, why the hell does this arbitrary designation matter? Programmatic functions are not mathematical functions, their purpose is completely different.
2
Aug 27 '16
Programmatic functions are not mathematical functions, their purpose is completely different.
That's very true. IMHO the article was great, but the example did not help make the point clear enough.
-1
u/vinnl Aug 28 '16
why the hell does this arbitrary designation matter?
My main takeaway, as I commented elsewhere, was that
there's more to purity then we often assume; that purity is a scale, and that e.g. types can help us edge a little bit more to the pure side of that scale.
16
u/kpmah Aug 27 '16
I would say this is a bit of a meaningless distinction and that the function is pure. You can always break assumptions if you try hard enough. e.g. in Haskell:
Prelude System.IO.Unsafe System.Random> let sum = foldl (+) 0
Prelude System.IO.Unsafe System.Random> sum [unsafePerformIO randomIO, unsafePerformIO randomIO]
1658109205626070070
Prelude System.IO.Unsafe System.Random> sum [unsafePerformIO randomIO, unsafePerformIO randomIO]
8004505404486503573
Prelude System.IO.Unsafe System.Random> sum [unsafePerformIO randomIO, unsafePerformIO randomIO]
-74009022551491285263
u/NewazaBill Aug 27 '16 edited Aug 27 '16
While I like a lot of the work that André Staltz has done with Cycle and whatnot, god has he been just a pedantic asshole lately. So I'm going to be even more pedantic.
His example can be boiled down to this:
let x = [Math.random(), Math.random(), Math.random(), Math.random()];
sum(x);
x = [Math.random(), Math.random(), Math.random(), Math.random()];
sum(x);
x = [Math.random(), Math.random(), Math.random(), Math.random()];
sum(x);Just because I changed what value x represents before each invocation, doesn't make sum impure. However, my program surely isn't pure, because each time I run it, it will output different results since Math.random() is calculated at runtime.
Now to get REALLY pedantic: the fact that we're passing an Array, which is a reference, DOES make the function impure. Consider this scenario:
const x = [1, 2, 3, 4];
doSomethingAsync().then(() => sum(x));
doAnotherAsyncThing().then(() => x.push(5));This is a much more nefarious problem, because x can now change while sum is being executed. So I can actually have a scenario where this happens:
1. Call sum: sum(x), where x = [1, 2, 3 ,4]
2. Sum begins adding: +1, +2, +3...
3. Suddenly, x is mutated: x.push(5)
4. Returned value: 15.The proper way to make the sum function pure would be:
function sum(...nums) {
if (!nums) return void 0;
var y = 0;
for (var i = 0; i < nums.length; i++) {
if (typeof nums[i] !== 'number') {
return void 0;
}
y += nums[i];
}
return y;
}
sum(1, 2); // 3
let x = [1, 2, 3, 4];
// destructured at call site, therefore x's mutations
// can not impact sum's output.
sum(...x);Anyway, I believe it's perfectly fine to use "pure" colloquially to mean that f(x) = y, as long as x is the same value. I just figured if we are going to be painfully pedantic, we may as well also be correct.
3
u/hahaNodeJS Aug 28 '16
let x = [Math.random(), Math.random(), Math.random(), Math.random()];
This is not the same as his example. Here, you have a set of random values that you keep changing. In Staltz's example, he has a set pointing to the random function.
1
u/vinnl Aug 28 '16
Exactly. Pure functions can return different outputs if the inputs are different, which is the case here.
1
u/hahaNodeJS Aug 29 '16
Right, but you're not addressing the same point the author is making. If you pass in the function
Math.random, the method should always return the same value. In the case for a functionf(x,y)that sums x, y, the returned value should be 0 if either x or y are non-numbers.In your example you're simply passing in different numeric values for
x,y,....1
5
u/tyroneslothtrop Aug 28 '16
x can now change while sum is being executed.
I don't think the single-threaded nature of JavaScript, the event loop, etc., actually allow for this sort of thing. The sum function will completely execute before some other async function can come in and mess with
x.0
u/vinnl Aug 28 '16
It is sort-of pedantic, but the point is not that you should care about the extreme cases of non-purity. All it's trying to say is that there's more to purity then we often assume; that purity is a scale, and that e.g. types can help us edge a little bit more to the pure side of that scale.
Or at least, that was my takeaway. His conclusion seems to be more about using more pedantic language, which I agree is not that relevant.
5
Aug 27 '16 edited Aug 27 '16
This is a philosophical question. JavaScript almost exists in a quantum state where you cannot tell if it is pure or impure, unless you use the code. That pretty much sums up the article.
2
Aug 28 '16
Except I don't think that's really true. Getting something's value is calling a function, so if that function's impure then yeah, any function that calls it will be impure. OTOH, as long as the function to get something's value is pure (ie 99.9% of cases) your pure function will actually be pure.
4
u/JamesWildDev Aug 27 '16
Does throwing an exception make a function impure? I wouldn't have thought of JavaScript exceptions as being particularly stateful; as long as they are thrown reproducibly due to arguments or constants (not due to external or internal state) that doesn't come across as impure to me. I guess the stack property is based on where you call it from.
4
3
Aug 28 '16
No function is pure because maybe the NSA is listening in on them or something even as absurd. Taken to the absolute, you can drain the practical value of any concept.
2
u/robpalme Aug 27 '16
It's easy for JS education to descend into shock and awe on how the language can be subverted or is unintuitive. The phrase "You don't know JS" is easy to deploy.
To demonstrate, here's another object you could pass into the protected sum() function to force it to be impure despite the checks...
var x = [0];
Object.defineProperty(x, 1, { get: ()=>x[0]++ });
sum(x); // 1
sum(x); // 52
2
Aug 28 '16
What? You mean overwriting default object behaviour may cause unexpected things to happen, such as making your pure functions impure? You might as well argue that your function could be impure because code somewhere else might overwrite it.
2
Aug 29 '16
Like everyone else, at first I thought he was just being pedantic about the word "pure." But as I read through it, it just reminded me of why I'm not 100% sold on JS and would love to have some type of safer environment (WASM?).
Consider the security implications of what he mentions. You can overwrite, and make crazy, any function call(incl. prototypes) available to the global scope. I mean this is stuff that any JS programmer knows, but doesn't want to think too deeply about.
It is most certainly the type of vector that any XSS could use to do all sorts of nasty stuff. You could write all your code correctly, avoid the global scope like the plague, sanitize inputs, and still someone could use what he is describing here to inject an undesirable function directly into the middle of your code... Just because you assumed a string literal was safe -- to read.
(I know... Why was foreign JS allowed in the first place? That is another issue... [Chrome extension, social engineering, JS console, etc?])
1
1
u/r2d2_21 Aug 27 '16
Math.random
That's cheating.
1
u/g_b Sep 19 '16
It could be any impure function instead of Math.random and the point would still stand.
1
u/r2d2_21 Sep 19 '16
OK, fair enough. Let me correct myself.
Messing with the internal workings of the language
That's cheating.
2
u/g_b Sep 19 '16
You can use any normal function without messing with anything.
function pure(x, callback) { return callback(x); }if you call a pure function with an impure function as parameter:
var y = 0; function impure(x) { return x + y++; } pure(1, impure); pure(1, impure);You get different output even though the arguments are the same.
The pure function will no longer be pure.
2
1
u/simcptr Aug 28 '16
It seems like "safe" might be a better word than "pure" to describe what he's talking about... "Given pathological input, will my function do what I expect?" is more a question of safety than purity I think.
-1
u/DrGarbinsky Aug 27 '16
Who cares if it is pure?
9
Aug 27 '16
Nobody, OP is just nitpicking and arguing about corner cases. If it behaves correctly for what I want it, it's pure enough to me.
5
u/misc_ent Aug 27 '16
Anyone who doesn't want side effects in their functions? Not trying to be snarky as that's literally the reason.
9
u/Prince_Houdini Aug 27 '16
I don't want side effects in my functions, but I don't care if my functions are "pure" in the sense the author uses here. The colloquial sense of pure - same input = same output in normal circumstances - is enough for me.
0
Aug 27 '16
[deleted]
16
Aug 28 '16 edited Feb 17 '17
L;-TobDQ4Er gzwHdFU:yp-e~o.;V)S;%x-0
z8Vt538KKk4UzA1&I($z49T#dJs0bGQzz[0Aoh)J1Cx5iV#JP&wb
1
u/bullet_darkness Aug 28 '16
Welp looks like every built in Math function is impure cause you can give it self-mutating/self-changing inputs. You can't ever trust Math.pow or Math.sin ever again since they won't necessarily give you a consistent output. /s
-3
u/DanielRosenwasser TypeScript Aug 27 '16
I'm not sure if you read through the whole thing, but that's sort of the point of the article. There's crazy stuff you can do in JS, but for the most part there are ways that are good enough to run with certain assumptions. Otherwise you'll vex over these ridiculous corner cases and never get anything done.
0
Aug 27 '16
[deleted]
1
u/vinnl Aug 28 '16
I think the main point is not that you should or could breach the contract, but rather to make you aware of the implicit parts of the contract, and how you can make some parts of it explicit as desired. For example, passing
undefinedornullwhen an actual value is expected is a breach of contract that does happen in practice, so you might want to defend against that.1
u/Reashu Aug 28 '16
Then arguing about function purity is just... I don't know the English idiom, but it's an unnecessary and uninteresting complication.
1
u/vinnl Aug 28 '16
I suppose that depends on how you learn best. For me, it helps to understand the bigger picture and abstract concepts so I will be able to generalise it to future situations.
1
u/Reashu Aug 28 '16
But purity is not the "big picture" of function contracts. It is a special case, and one of the more thorny ones, to boot.
1
u/vinnl Aug 28 '16
But there is a scale of contracts in terms of how pure your function is, and they're easy to overlook - this article focuses on that bigger picture rather than just passing in
undefined. But yes, I consider a look at more extensive typing systems and their encoding of function contracts (i.e. an even bigger picture) to be interesting as well.1
u/neophilus77 Aug 29 '16
You shouldn't have to defend against bad data, bad data is a symptom of a bug somewhere else
1
13
u/reeferd Aug 27 '16
If the input to a function always is random, then the input is never the same - or am I missing something here?