r/purescript • • 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

7 comments sorted by

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?

2

u/hdgarrood Jun 28 '17

It's because that means that we get predictable overflow behaviour, ie we get actual int32s, rather than just doubles which happen to be integers. Doubles start to behave very strangely around 253, you get things like x+1 comparing equal to x.

2

u/rightfold Jun 28 '17

This isn't "defaulting to 0". It's bitwise OR, not logical OR.