将MaybeT与`join`一起使用 [英] Using MaybeT with `join`

查看:94
本文介绍了将MaybeT与`join`一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看MaybeT变压器:

ghci> let x = MaybeT $ Just 1234
ghci> let y = runMaybeT x
ghci> :t y
y :: Num (Maybe a) => Maybe (Maybe a)

现在我想获取内部的Maybe a,但是join无效.

Now I want to get the inner Maybe a, but join does not work.

ghci> join y

<interactive>:53:1:
    No instance for (Num (Maybe a0)) arising from a use of `it'
    In a stmt of an interactive GHCi command: print it

如何获得内部Maybe a值?

推荐答案

您没有正确使用MaybeT构造函数.查看类型签名:

You are not using the MaybeT constructor correctly. Look at the type signatures:

MaybeT    ::            m   (Maybe a) -> MaybeT m a
                        |   |       |
                      /-+-\ \---+---/
                      |   |     |
Just 1234 :: Num x => Maybe     x

因此:

m := Maybe
x := Maybe a

因此:

MaybeT $ Just 1234 :: Num (Maybe a) => MaybeT Maybe a

因此,这里Maybe a应该是Num的一个实例,这显然是错误的.选项类型不是数字.为什么会出现这个问题?

So here Maybe a is expected to be an instance of Num which is clearly wrong. An option type is not a number. Why does this problem arise?

考虑数字文字1234.数字文字是Haskell中的有界多态值.因此,它们的类型为Num x => x.换句话说,1234可以是任何类型,具体取决于上下文,只要该类型是Num的实例即可(例如IntIntegerDouble).

Consider the numeric literal 1234. Numeric literals are bounded polymorphic values in Haskell. Hence, they have the type Num x => x. In other words 1234 can be of any type depending upon the context as long as that type is an instance of Num (e.g. Int, Integer, Double).

在您的代码中,多态类型x被实例化为Maybe a,这就是为什么Haskell期望Maybe aNum的实例.

In your code, the polymorphic type x is instantiated to Maybe a which is why Haskell expects Maybe a to be an instance of Num.

我认为您真正想做的是:

I think what you really want to do is this:

MaybeT             ::                     m (Maybe a) -> MaybeT m a

return $ Just 1234 :: (Num a, Monad m) => m (Maybe a)

因此:

MaybeT $ return $ Just 1234 :: (Num a, Monad m) => MaybeT m a

现在您可以轻松提取内部Maybe a:

Now you can easily extract the inner Maybe a:

runMaybeT $ MaybeT $ return $ Just 1234 :: (Num a, Monad m) => m (Maybe a)

由于内部Maybe a值包装在monad中,因此您只需使用>>=提取Maybe a:

Since the inner Maybe a value is wrapped in a monad all you need to do is use >>= to extract the Maybe a:

(runMaybeT $ MaybeT $ return $ Just 1234) >>= \x -> do
    -- do something with x
    -- x :: Maybe a

您也可以使用do表示法编写该代码:

You could also write this using the do notation:

do
    x <- runMaybeT $ MaybeT $ return $ Just 1234
    -- do something with x
    -- x :: Maybe a

希望有帮助.

这篇关于将MaybeT与`join`一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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