将 (Maybe a, b) 转换为 Maybe (a,b)

Converting (Maybe a, b) to Maybe (a,b)

是否有一种简单的方法(无需重新发明轮子)从 (Maybe a, b) 转换为 Maybe (a,b)。我查看了 Traversable 但无法正常工作。

是的。函子。

solution :: (Maybe a, b) -> Maybe (a, b)
solution (a, b) = fmap (\q -> (q, b)) a

或者,在 pointfree 风格中:

solution = uncurry $ flip $ fmap . flip (,)

此外,正如@Bakuriu 所说,如果您启用了 TupleSections,并且导入了 Control.Applicative,它会变得 真的 容易:

solution (a, b) = (, b) <$> a

了解更多 here

“无需重新发明轮子”是什么意思?创建这样一个函数最直接的方法如下:

f :: Maybe a -> b -> Maybe (a, b)
f Nothing  _ = Nothing
f (Just a) b = Just (a, b)

g :: (Maybe a, b) -> Maybe (a, b)
g = uncurry f

希望对您有所帮助。

您也可以使用 Bitraversable:

bitraverse id pure :: (Bitraversable t, Applicative f) => t (f c) d -> f (t c d)

专门针对

bitraverse id pure :: (Maybe a, b) -> Maybe (a, b)

以下适用于 lens

> import Control.Lens
> _1 id (Just 1, 2)
Just (1, 2)