Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Haskell中的do上下文中应用构造函数_Haskell_Constructor - Fatal编程技术网

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

在Haskell中的do上下文中应用构造函数,haskell,constructor,Haskell,Constructor,鉴于以下声明 data MyCustomString=MyCustomString字符串派生(Show,Eq) getSomeString::IO字符串 我想在do上下文中将getSomeString的输出处理为IO MyCustomString: do 通常的方法是: do cs_one <- MyCustomString <$> getSomeString cs_two <- MyCustomString <$> getSomeStrin

鉴于以下声明

data MyCustomString=MyCustomString字符串派生(Show,Eq)
getSomeString::IO字符串
我想在
do
上下文中将
getSomeString
的输出处理为
IO MyCustomString

do
通常的方法是:

do
    cs_one <- MyCustomString <$> getSomeString
    cs_two <- MyCustomString <$> getSomeString
由于单子是函子,它专门用于单子的IO
如下:

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

它在IO monad下应用了一个函数,在这种情况下,将您的
IO字符串
转换为
IO MyCustomString

,因为
getSomeString
返回一个
IO字符串
,而构造函数需要一个裸字符串,所以不能将构造函数应用于
getSomeString

首先,您必须获得实际生成的字符串,然后可以将其包装到构造函数中:

do
    cs_one_str <- getSomeString
    let cs_one = MyCustomString cs_one_str
    ...
或其操作员别名


你真是太棒了。我确实需要练习我的函子:)
do
    cs_one_str <- getSomeString
    let cs_one = MyCustomString cs_one_str
    ...
    cs_one <- fmap MyCustomString getSomeString
    cs_one <- MyCustomString <$> getSomeString