2014-01-14 45 views
3

此代碼不進行類型檢查:字節字符串預期不同的字節串

import Network.HTTP.Conduit 
import qualified Data.ByteString.Char8 as BS 

main :: IO() 
main = do 
    resp <- simpleHttp "http://www.google.com" 
    putStrLn $ BS.unpack resp 

拋出以下錯誤:

Couldn't match expected type `BS.ByteString' 
      with actual type `Data.ByteString.Lazy.Internal.ByteString' 
In the first argument of `BS.unpack', namely `resp' 
In the second argument of `($)', namely `BS.unpack resp' 
In a stmt of a 'do' block: putStrLn $ BS.unpack resp 
Failed, modules loaded: none. 

如何解決這一問題?更改爲其他ByteString變體不起作用。

simpleHttp函數的類型是這樣的:simpleHttp :: Control.Monad.IO.Class.MonadIO m => String -> m Data.ByteString.Lazy.Internal.ByteString。所以我嘗試獲取IO monad中的ByteString並嘗試使用unpack,但這會導致錯誤。

+0

什麼是進口限定的Data.ByteString.Lazy作爲BS'? – viorior

+0

@actionior它引發一個不同類型的錯誤。 – Sibi

回答

3

有兩個單獨的ByteString模塊,一個用於懶惰的ByteStrings,另一個用於嚴格的ByteStrings。 simpleHTTP返回一個懶惰的字節串,但是你導入了嚴格的bytestring模塊,所以unpack期待一個嚴格的字節串。

嘗試改變

import qualified Data.ByteString.Char8 as BS 

import qualified Data.ByteString.Lazy.Char8 as BS 

這就是說,你需要的,如果你使用的字節字符串模塊的CHAR8版本,因爲字符串<要小心 - >字節串轉換僅在使用ASCII編碼時纔有效。我會建議converting your bytestrings to Text與適當的編碼功能,然後打印。

+0

將其更改爲'Lazy'會引發另一個錯誤:「無法與'Char'匹配'GHC.Word.Word8'類型 預期類型:字符串 實際類型:[GHC.Word.Word8] 在返回類型'BS.unpack'的調用 在'($)'的第二個參數中,即'BS.unpack resp' 在'do'塊的標記中:putStrLn $ BS.unpack resp Failed,modules loaded : 沒有。」 – Sibi

+0

@Sibi:word8的東西與使用模塊的char8版本有關。看我的編輯。 – hugomg