开发者

Writing [Bool] to binary file using Haskell

开发者 https://www.devze.com 2023-04-11 23:47 出处:网络
Working in Haskell, I am trying to write a big list of booleans to a binary file. I can write Word8 (which is a 8 bit word) to file, but can\'t figure out how to convert from an list of eight Bool t

Working in Haskell, I am trying to write a big list of booleans to a binary file.

I can write Word8 (which is a 8 bit word) to file, but can't figure out how to convert from an list of eight Bool to a Word8.

Here's what I have so far:

toByte :: [Bool] -> Word8
toByte list = toByteh list 0 0

toByteh :: [Bool] -> Int -> Word8 -> Word8
toByteh list 8 _ = 0
toByteh list i result 
    | head list == True = toByteh (tail list) (i + 1) (result .|. (2^i :: Word8))
    | otherwise = toByte_h (tail list) (i + 开发者_运维问答1) result

When I use this I just get a 0 byte. Can anyone see where this isn't working? Or are there better ways of doing this?


You're counting up i from 0 and when you reach 8, you return 0. I think you meant to return result instead:

toByteh list 8 result = result


It is always nice to write such functions, but if you start feeling bored, you may also

toByte = foldl (\word\bit -> 2*word + (if bit then 1 else 0)) 0 

(Here, the head of the list is taken as the lowest bit, reverse if you dont like.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号