Haskell Monad返回类型 [英] Haskell monad return type

查看:63
本文介绍了Haskell Monad返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些编程工作,但我无法进入单子.我对IO功能做了一些改进,但现在我肯定迷路了...

I'm trying to do a bit of programming and I can't get into monads. I've advanced a bit with IO functions, but now I'm definitely lost...

我有一个从网络加载的XML字符串(因此它被存储"在 IO String 中).因此,我需要一个 do 块才能加载到通用String中.

I've got a XML string that was loaded from the network (so it's "stored" in IO String). Because of this, I need a do block to load to common String.

foo :: IO String -> Nothing
foo xmlio = do
    xmlio <- xml
    -- do some magic

我已经实现了另一个函数,该函数采用纯字符串并返回纯XML元素.它的作用还更多,但让我们简化一下,因为它对这个问题并不重要.

I've already implemented another function that takes pure string and returns pure XML element. It does a bit more, but let's simplify that as it's not important for this question.

import Text.XML.Light
import Text.XML.Light.Input

toxml :: String -> Maybe Element
toxml s = parseXMLDoc s

现在,我试图将两者结合起来以接受IO字符串并返回"IO元素".

Now I tried to combine these two to accept an IO String and to return an "IO Element".

toxmlio :: IO String -> ??? Maybe Element
toxmlio s = do
    pures <- s
    let toReturn = parseXMLDoc s
    return s

返回函数的类型为(根据ghci):

The return function's type is (according to ghci) :

let foo = "<foo>bar</foo>"
:t return (parseXMLDoc foo)
    >> return (parseXMLDoc foo) :: Monad m => m (Maybe Element)

但是如果我将函数的标题更改为

But if I change the header of my function to

toxmlio :: IO String -> Monad (Maybe Element)
toxmlio s = do
    pures <- s
    let toReturn = parseXMLDoc s
    return s

我收到编译错误

Kind mis-match
The first argument of `Monad' should have kind `* -> *',
but `Maybe Element' has kind `*'
In the type signature for `xmlio':
  xmlio :: String -> Monad (Maybe Element)

有人知道如何解决此问题吗?还是我完全迷失了,Haskell用另一种方式呢?谢谢您的回答.

Does anyone have any idea how to solve this issue? Or am I completely lost and haskell does this another way? Thank you for your answer.

推荐答案

看起来像您想要的:

toxmlio :: IO String -> IO (Maybe Element)
toxmlio s = do
    pures <- s
    let toReturn = parseXMLDoc pures
    return toReturn

但是您可以使用 liftM :

toxmlio :: IO String -> IO (Maybe Element)
toxmlio = liftM parseXMLDoc

您可以使其更加通用,因为 liftM 不依赖于特定的monad类型:

You could make it even more general, since liftM does not depend on a particular monad type:

toxmlio :: Monad m => m String -> m (Maybe Element)
toxmlio = liftM parseXMLDoc

这篇关于Haskell Monad返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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