有没有办法自动上下班?

发布于 2025-01-25 00:50:19 字数 512 浏览 3 评论 0 原文

我已经写了一个程序来将 从一对中拉出:

deMaybe :: (a, Maybe b) -> Maybe (a, b)
deMaybe (_, Nothing) = Nothing
deMaybe (x,Just y) = Just (x, y)

我知道也许是单数,(,)a 是函数(除其他类型)。我想知道我是否缺少一个更高级别的功能,例如:

commute :: (Functor f, Monad m) => f (m a) -> m (f a)

我的问题是:我可以用更通用的类型签名编写 demaybe ,例如假设 colmute ,承认我试图使一个函子通过另一个函子?可以使用诸如 fmap >> = pure ,& c。

I have written a program to pull a Maybe out of a pair:

deMaybe :: (a, Maybe b) -> Maybe (a, b)
deMaybe (_, Nothing) = Nothing
deMaybe (x,Just y) = Just (x, y)

I know that Maybe is a monad and (,) a is a functor (among other typeclasses). I'm wondering if there is a higher-level function I'm missing, such as:

commute :: (Functor f, Monad m) => f (m a) -> m (f a)

My question is: can I write deMaybe with a more general type signature like that of the hypothetical commute, acknowledging that I am trying to commute one functor past another? Can this be done using functions such as fmap, >>=, pure, &c.?

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

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

发布评论

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

评论(1

揽清风入怀 2025-02-01 00:50:19

您可以与 ,但这需要 traverable 。对于 t〜(b,) m〜也许,因此起作用:

Prelude> sequence (2, Just 3)
Just (2,3)
Prelude> sequence (2, Nothing)
Nothing

a traverable 是可以转换的数据结构的类型到具有相同形状的项目。我们需要它来构造一个2键盘(或列表,或类似的东西)。

或者我们可以使用 AS @chepner说,这更一般,因为所有 MONAD s均为 appricative s:s::

Prelude> sequenceA (2, Just 3)
Just (2,3)
Prelude> sequenceA (2, Nothing)
Nothing

You can work with sequence :: (Traversable t, Monad m) => t (m a) -> m (t a), but this requires a Traversable. For t ~ (b, ) and m ~ Maybe, this thus works as:

Prelude> sequence (2, Just 3)
Just (2,3)
Prelude> sequence (2, Nothing)
Nothing

A Traversable is a typeclass for data structures that can be transformed to an item with the same shape. We need this to construct thus a 2-tuple (or list, or something similar).

or we can use sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) as @chepner says, which is more general since all Monads are also Applicatives:

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