簡體   English   中英

有關IO和符號的混淆

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM