I'm aware that with Data.Bits I can do bitwise manipulation on anything with an instance of Bits. That however is not what I want. I explicitly want to manipulate a list of Bools which represent the bit value at each bit index.
More precisely I want to manipulate the bits of a 1-byte integer.
I have managed to get this to work using map/testBit and foldl'/setBit. Which you can see from my tests in ghci below:
λ import Data.Bits
λ import Data.List
λ let convertToBits :: Int -> [Bool] ; convertToBits x = map (testBit x) [7,6..0]
λ let convertFromBits :: [Bool] -> Int ;
convertFromBits bs = foldl' (\acc (i,b) -> if b then setBit acc i else acc) 0 $ zip [7,6..0] bs
λ convertToBits 255
[True,True,True,True,True,True,True,True]
λ convertToBits 2
[False,False,False,False,False,False,True,False]
λ convertFromBits [False,False,False,True,True,False,False,True]
25
λ convertFromBits $ convertToBits 255
255
λ convertFromBits $ convertToBits 10
10
However this doesn't feel like a particularly great implementation. I'm wondering if this (or something similar) might be in standard library?
EDIT ------
A quick final note, even though I have answered the question below, I thought I'd add a bit more in case anyone stumbles on this and knows a better answer. I'll be storing all of the bits in a UArray which will bit-pack the Bool values.
In thinking about it, what would be really good is a function that converts a Word8 into a UArray ix Bool. I'd like to think there is some efficient / simple way to do this but I don't know enough about the low level stuff to work it out.
Word8certainly seems a more economical choice for this than[Bool]on the surface. Can you say a bit more about why you prefer the latter?UArrayand from what I've read it should bit pack theBools. Though in their temporary[Bool]state they will take up an unnecessary amount of memory. Reading the bits will trigger the activation of Nodes in a neural network, which will then run its own processing of the inputs. The activated outputs nodes get read as bit values that trigger anIntoutputs.Word8 -> Array ix BoolorWord8 -> [Bool]that could break aWord8into its constituent bits in one go (where as my map and fold require 8 steps each).bitwisesuggests to me that this is the most practical approach. Assuming there is nothing else than the answer to my question "I'm wondering if this (or something similar) might be in standard library?" is "No".