使用 Haskell 将 [Bool] 写入二进制文件
在 Haskell 中工作,我试图将一个大的布尔值列表写入二进制文件。
我可以将 Word8(这是一个 8 位字)写入文件,但无法弄清楚如何从八个 Bool 列表转换为 Word8。
这是我到目前为止所得到的:
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
当我使用它时,我只得到一个 0 字节。谁能看出这在哪里不起作用吗? 或者有更好的方法来做到这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您从
0
开始计数i
,当达到8
时,返回0
。我认为你的意思是返回结果
:You're counting up
i
from0
and when you reach8
, you return0
. I think you meant to returnresult
instead:编写这样的函数总是很好,但是如果你开始感到无聊,你也可以
(这里,列表的头部被视为最低位,如果你不喜欢,则相反。)
It is always nice to write such functions, but if you start feeling bored, you may also
(Here, the head of the list is taken as the lowest bit, reverse if you dont like.)