Skip to content

Instantly share code, notes, and snippets.

@garious
Created November 21, 2012 23:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save garious/4128503 to your computer and use it in GitHub Desktop.
fixed-length vectors?
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment