Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `Bits` depend on `Num`?

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?

like image 804
hvr Avatar asked Jul 03 '11 13:07

hvr


People also ask

What determines the number of bits?

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.

Why are there 8 bits in a byte and not 10?

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.

Why does the size of integer depend on the machine architecture?

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.

Why do we normally use int size of 4 bytes instead of 8 bytes?

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.


1 Answers

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.

like image 175
Don Stewart Avatar answered Oct 23 '22 20:10

Don Stewart