I've been coding my own bit-vectors (represented as strict tuples over Word64 values) as an exercise in time and space optimizations and wanted to define instances of the Bits typeclass for them, but then I noticed that the class declaration for Bits is defined as follows:
class Num a => Bits a
To workaround this, I'm defining a fake Num instance as well, made up mostly of error-valued functions as a hack, but this doesn't feel right...
What was the rationale of depending on the Num type-class for bit-wise operations? Wouldn't it make more sense to be able to have Bits instances independen from having to declare a Num instance as well?
When looking for the number of bits needed to represent a given number of characters (letters, numbers, or symbols), you need to look at the powers of 2. For example, the reason that 5 bits are required to represent 27 characters is that 2^2=4 (4 is not enough), 2^3 is 8 (still not enough)… 2^5 is 32.
The byte was originally the smallest number of bits that could hold a single character (I assume standard ASCII). We still use ASCII standard, so 8 bits per character is still relevant.
It wastes space. If required, one can be 64 bits long and still have int be 32 bits. Otherwise, leave only long long for those cases where 64-bit integers are required. Most current implementations do the previous 64 bits long.
So the reason why you are seeing an int as 4 bytes (32 bits), is because the code is compiled to be executed efficiently by a 32-bit CPU. If the same code were compiled for a 16-bit CPU the int may be 16 bits, and on a 64-bit CPU it may be 64 bits.
Bits depends on Num, because Num provides numeric literals and negation, which are used in the default methods for Bits, like so:
bit :: Int -> a
bit i               = 1 `shiftL` i
testBit           :: a -> Int -> Bool    
x `testBit` i       = (x .&. bit i) /= 0        
If there were no default methods, you could imagine getting away without the Num constraint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With