我有这个非常简单的功能
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)
where jsonFile
是我的硬盘驱动器上文件的路径(请原谅缺少 do 符号,但我发现这更容易使用)
我的问题是;有没有办法让我放弃IO
部分以便我可以单独使用字节串?
我知道你可以对某些单子进行模式匹配,例如Either
and Maybe
来了解他们的价值观,但是你可以做类似的事情吗IO
?
或者用不同的方式表达:我有办法做到吗?readJFile
return Maybe Response
没有IO?
为了扩展我的评论,您可以这样做:
getJson :: IO B.ByteString
getJson = B.readFile jsonFile -- as before
readJFile :: B.ByteString -> Maybe Response -- look, no IO
readJFile b = case eitherDecode b of
Left err -> Nothing
Right ps -> Just ps
最后,您再次将所有内容组合到一个 IO 操作中:
getAndProcess :: IO (Maybe Response)
getAndProcess = do
b <- getJson
return (readJFile b)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)