将MaybeT与`join`一起使用

编程入门 行业动态 更新时间:2024-10-24 12:25:56
本文介绍了将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的实例即可(例如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`一起使用

本文发布于:2023-07-09 02:24:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1082880.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:MaybeT   join

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!