我有一个非常简单的函数
import qualified Data.ByteString.Lazy as B
getJson :: IO B.ByteString
getJson = B.readFile jsonFile
readJFile :: IO (Maybe Response)
readJFile = parsing >>= (\d ->
case d of
Left err -> return Nothing
Right ps -> return (Just ps))
where parsing = fmap eitherDecode getJson :: IO (Either String Response)
jsonFile
是我硬盘上文件的路径(抱歉没有使用do-notation,但我发现这样更清晰)。
我的问题是:是否有一种方法可以摆脱 IO
部分,以便我可以仅使用bytestring处理?
我知道您可以在某些单子上进行模式匹配,例如 Either
和 Maybe
,以获取它们的值,但您是否可以使用 IO
进行类似的操作?
或者换句话说:是否有一种方法使 readJFile
在没有IO的情况下返回 Maybe Response
?
B.ByteString -> ...
),然后使用单个IO操作将读取和处理组合起来。 - kosmikusreadJFile
这个函数涉及到IO操作,因此它必须有一个IO类型。但是你可以按照我之前所说的,使用bytestring对其进行抽象处理。 - kosmikusgetJson
函数执行io操作,readJFile
函数只是解释接收到的数据。 - Electric Coffee