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/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.