有没有办法从IO monad打开一个类型? [英] Is there a way to unwrap a type from an IO monad?

查看:160
本文介绍了有没有办法从IO monad打开一个类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个非常简单的功能

I have this very simple function

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 是路径到我的硬盘上的一个文件(原谅我没有写法,但我发现这个更清楚了)

where jsonFile is a path to a file on my harddrive (pardon the lack of do-notation, but I found this more clear to work with)

我的问题是;有没有办法让我放弃 IO 部分,这样我就可以单独使用bytestring了?

my question is; is there a way for me to ditch the IO part so I can work with the bytestring alone?

我知道您可以在某些monad上进行模式匹配,例如 可能以获取其值,但是您可以执行类似的操作与 IO

I know that you can pattern match on certain monads like Either and Maybe to get their values out, but can you do something similar with IO?

或者说不同:有没有办法让我做 readJFile 返回可能没有IO的响应

Or voiced differently: is there a way for me to make readJFile return Maybe Response without the IO?

推荐答案

为了扩展我的评论,以下是你如何做到这一点:

To expand on my comments, here's how you can do it:

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操作中:

In the end, you combine everything in one IO action again:

getAndProcess :: IO (Maybe Response)
getAndProcess = do
  b <- getJson
  return (readJFile b)

这篇关于有没有办法从IO monad打开一个类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆