Skip to content

negate method of Num instance on Word coerces to Int?

I was doing a deep dive into Intmap.Internal.lookup for #20069 and noticed redundant int2Word# and word2Int# calls in the stg of lookup. You can find the whole story on this issue in the containers library.

While making the patched version I saw that negate on Word is defined as:

instance Num Word where
...
    negate (W# x#)         = W# (int2Word# (negateInt# (word2Int# x#)))
...

In that it also coerces to an Int to negate!

Clearly there must be a better way. I'm unsure if these coercions actually make any kind of difference. From the containers issue above there was no observable performance difference on lookup and from reading Cmm it looks like these get optimized or converted to no-ops anyway.

In any case, shouldn't negate be defined as a 2's complement? That is:

instance Num Word where
...
    negate x               = W# ((complement x) `plusWord#` (int2Word# 1))
...
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information