haskell - 在 Haskell 的 do 上下文中应用构造函数

给出以下声明

data MyCustomString = MyCustomString String deriving (Show, Eq)

getSomeString :: IO String

我想在 do 上下文中将 getSomeString 的输出处理成 IO MyCustomString:

do
    cs_one <- getSomeString
    cs_two <- getSomeString

    -- at this point, `cs_one` and `cs_two` are of type `String`
    -- how to construct them into `MyCustomString` instead with no additional lines?

但是,getSomeString 返回一个 String 而不是 MyCustomString。我如何使用 MyCustomString 构造函数,以便 cs_onecs_two 在代码的这一点上都是 MyCustomString ?

我已经试过了,没有用:

-- this does not work
do
    MyCustomString cs_one <- getSomeString
    MyCustomString cs_two <- getSomeString

-- this neither
do
    cs_one <- MyCustomString getSomeString
    cs_two <- MyCustomString getSomeString

最佳答案

通常的做法是:

do
    cs_one <- MyCustomString <$> getSomeString
    cs_two <- MyCustomString <$> getSomeString

<$>运算符是 fmap 的同义词并有签名:

(<$>) :: Functor f => (a -> b) -> f a -> f b

由于 monad 是仿函数,它专门针对 monad IO作为:

(<$>) :: (a -> b) -> IO a -> IO b

它在 IO monad“下”应用了一个函数,在本例中是将你的 IO String进入 IO MyCustomString .

https://stackoverflow.com/questions/64447428/

相关文章:

python-3.x - Python Pandas : groupby one column, 只

node.js - docker-compose npm install && npm start

javascript - 在 React Native 中安排本地通知不起作用

c++ - 仅当使用 unordered_map 而不是 vector 时,将 const 作为此参

python - Windows 上的 Gcloud 命令(使用 git bash)正在记录错误 :

vue.js - 如何制作可点击的带有悬停效果的q卡?

java - 如何使用 void set 方法在静态常量帮助程序类中创建对象?

python - 在Python中随机生成二维列表

react-native - React native 每次打开页面时如何执行函数

azure-devops - Azure Devops - Terraform 任务失败并出现错误