[英]Confusion about IO and do notation
我是Haskell的初學者,對我編寫的這段代碼感到困惑
readRecords :: String -> [Either String Record]
readRecords path = do
f <- B.readFile path
map parseLogLine (C8.lines f)
但這給了我這個錯誤:
Main.hs:15:10:
Couldn't match type `IO' with `[]'
Expected type: [C8.ByteString]
Actual type: IO C8.ByteString
In the return type of a call of `B.readFile'
In a stmt of a 'do' block: f <- B.readFile path
In the expression:
do { f <- B.readFile path;
map parseLogLine (C8.lines f) }
parseLogLine
的類型簽名為parseLogLine :: B8.ByteString -> Either String Record
。
我完全感到驚訝。 B.readFile path
應該返回IO ByteString
,因此f
應該是ByteString
。 C8.lines f
應該返回[ByteString]
而map應該return [Either String Record]
。
我哪里錯了?
首先,將readRecords
定義為錯誤的類型。 如果do
塊將在IO
monad中工作,則它將生成IO
值,但您已將其定義為返回[]
monad中的[]
[Either String Record]
。 這意味着您不能調用B.readFile
返回IO
而不會觸發您收到的類型錯誤。
一旦你解決這個問題,你會發現, map
上做塊的最后一行表達有錯誤的類型,因為它產生[Either String Record]
當它應該產生IO [Either String Record]
。 將呼叫return
以解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.