Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing [Bool] to binary file using Haskell

Tags:

haskell

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?

like image 407
Scott Newson Avatar asked Aug 20 '26 17:08

Scott Newson


2 Answers

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
like image 185
hammar Avatar answered Aug 23 '26 09:08

hammar


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.)

like image 30
Ingo Avatar answered Aug 23 '26 08:08

Ingo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!