public
Created

fixed-length vectors?

  • Download Gist
BitVectorTest.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
import qualified Data.Vector.Unboxed as V
import Data.Bits(setBit)
import Data.Word(Word8)
 
main :: IO ()
main = do
assertEqual 0x8c $ byte (bitsLE "0011" V.++ bitsLE "0001")
putStrLn "passed"
 
-- Create a bit-vector from a little-endian string of 1's and 0's
bitsLE :: String -> V.Vector Bool
bitsLE = V.map (/= '0') . V.fromList
 
-- Convert to Word8. Bits past first 8 silently ignored.
byte :: V.Vector Bool -> Word8
byte = V.ifoldl' setWhen 0
where
setWhen acc _ False = acc
setWhen acc i True = setBit acc i
 
assertEqual :: (Eq a, Show a) => a -> a -> IO ()
assertEqual actual expected
| actual == expected = return ()
| otherwise = error $ "assertion failed\n"
++ " expected: " ++ show expected ++ "\n"
++ " but got: " ++ show actual

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.