如何将 Maybe 值注入 MaybeT

发布于 2024-12-23 10:42:00 字数 303 浏览 2 评论 0原文

假设我有一些 foo :: Maybe Int 并且我想将它绑定到例如 bar :: Int ->; MaybeT (Writer String) Int,这样做的惯用方法是什么?

我可以定义自己的 liftMaybe 函数,然后使用它,例如:

let liftMaybe = maybe (fail "Nothing") return in liftMaybe foo >>= bar

但是有没有更惯用(或至少简洁)的方法来做到这一点?

Say I have some foo :: Maybe Int and I want to bind it for example with bar :: Int -> MaybeT (Writer String) Int, what would be the idiomatic way to do that?

I could define my own liftMaybe function, and then use that, like:

let liftMaybe = maybe (fail "Nothing") return in liftMaybe foo >>= bar

But is there a more idiomatic (or at least concise) way to do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初吻给了烟 2024-12-30 10:42:00
MaybeT . return :: (Monad m) => Maybe a -> MaybeT m a

我认为很遗憾它没有标准名称,但是 a hoogle 搜索,我们看到 relude 包使用 hoistMaybe

hoistMaybe :: Applicative m => Maybe a -> MaybeT m a

更通用的形式是

liftMaybe :: (MonadPlus m) => Maybe a -> m a
liftMaybe = maybe mzero return

优于使用 fail 的形式。我只是将它放在某个方便的模块中。

MaybeT . return :: (Monad m) => Maybe a -> MaybeT m a

I think it's a shame it doesn't have a standard name, however doing a hoogle search, we see that the relude packages uses hoistMaybe:

hoistMaybe :: Applicative m => Maybe a -> MaybeT m a

A more general form is

liftMaybe :: (MonadPlus m) => Maybe a -> m a
liftMaybe = maybe mzero return

which is preferable to the use of fail. I'd just put it in a convenient module somewhere.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文