r/purescript • u/ia2014 • Jun 28 '17
Question about "| 0" in generated JavaScript
The following PureScript code:
fibs 0 = 1
fibs 1 = 1
fibs n = fibs (n-1) + fibs (n-2)Compiles to the following JavaScript:
var fibs = function (v) {
if (v === 0) {
return 1;
};
if (v === 1) {
return 1;
};
return fibs(v - 1 | 0) + fibs(v - 2 | 0) | 0;
};Which all makes perfect sense, except the "| 0"s seem a bit unnecessary. Is it an optimisation? Or to make it robust to undefined or NaNs? Thanks in advance!
By the way, I think it's a fantastic achievement that the generated code is as readable as it is!
I also posted this in Stack Overflow but didn't get a reply - maybe it will have more visibility here.
4
Upvotes
View all comments
Show parent comment
2
u/ia2014 Jun 28 '17
Although your example is in the interpreter it's still the PureScript type checking that is catching the error, not any run-time behaviour of the generated code. But you make an interesting point that it may be to make the generated code robust when used from unsafe (native) JS. Still not sure I see the point in this particular case though. Maybe there's another example where the defaulting to 0 makes more sense?