2016-09-29 31 views
0

我的打印語句一直拋出錯誤,不太明白髮生了什麼。如何在Haskell中打印出二進制文件中的字節?

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: "' 
+2

關於術語的說明。 'print'不是「拋出[錯誤]」,這意味着你正在執行程序。發生了什麼事是編譯器發出關於print語句的類型檢查錯誤。 –

回答

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) 

代替

+0

如果我將輸入!! 0存儲到變量中,然後在putStrLn中使用它,我會得到「無法與具有'IO a0'」錯誤的'Word8'類型匹配。 – Vlam

+0

執行此數據庫類型< - input !! 0分配變量,然後執行Prelude.putStrLn $「DBType:」++ show(databasetype)以打印輸出。獲取「無法匹配類型'Word8'與'IO a0'」錯誤。 – Vlam

+1

@Vlam啊。所以你會希望'let databasetype = input !! 0'作爲賦值。 '<--'實際上是do-notation的一部分,這是不同的。我建議你稍微閱讀一下do-notation。 – Alec

相關問題