如何在Haskell中打印出二进制文件中的字节?

时间:2016-09-29 05:46:56

标签: haskell binary

我的print语句一直在抛出错误,不能真正理解发生了什么。

import Data.ByteString.Lazy as BS
import Data.Word
import Data.Bits

readByte :: String -> IO [Word8]
readByte fp = do
    contents <- BS.readFile fp
    return $ Prelude.take 5 $ unpack contents

main :: IO ()
main = do
    input <- readByte "DATA.BIN"
    print "Byte 0: " ++ [input!!0]

获得以下错误:

Couldn't match expected type `[()]' with actual type `IO ()'
In the return type of a call of `print'
In the first argument of `(++)', namely `print "Byte 0: "'

1 个答案:

答案 0 :(得分:2)

Haskell正在将print "Byte 0: " ++ [input!!0]解析为(print "Byte 0: ") ++ [input!!0],这可能不是您想要的。你可能想要

main :: IO ()
main = do
    input <- readByte "DATA.BIN"
    putStrLn $ "Byte 0: " ++ show (input!!0)

代替