将MaybeT与`join`一起使用 [英] Using MaybeT with `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
的实例即可(例如Int
,Integer
,Double
).
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 a
是Num
的实例.
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屋!