Reputation: 3358
I want to use a bitfield with 32 bits that store the result of the last 32 computations in sequence. E.g. 0110 ... would be fail pass pass fail ... . Ideally the latest result should just be pushed on the bitfield whilst then the oldest result "falls away" on the other side. For example: 0110 where 1 is the newest result should become 1101.
I am struggling with the use of Data.Bits
and don't know how to initialise / create a bitfield. The errors I get are all somewhat similar to
No instance for (Bits a0) arising from a use of `bitDefault'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Bits Int -- Defined in `Data.Bits'
instance Bits Integer -- Defined in `Data.Bits'
instance Bits GHC.Types.Word -- Defined in `Data.Bits'
Once I add type signatures GHC tells me back about
Illegal literal in type (use -XDataKinds to enable): 32
or similar errors. Sometimes it requests the Kind *
etc.. I think this is some very basic what I am missing here. How can I create a BitField?
Upvotes: 1
Views: 1247
Reputation: 5083
Just use Word32
from Data.Word
as a bitmap. It is a type that has Bits
instance and thus you can use methods of typeclass Bits
on it:
import Data.Bits
import Data.Word
type Bitmap32 = Word32
bitmap :: Word32
bitmap = 0 -- initialize with zeros
...
testBit bitmap 10 -- test 10th bit
...
pushNewBit :: Bool -> Bitmap32 -> Bitmap32
pushNewBit b bitmap = (bitmap `shiftL` 1) .|. (if b then 1 else 0)
Upvotes: 3