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

时间:2015-06-28 14:44:57

标签: function haskell tuples type-conversion maybe

(Maybe a, b)转换为Maybe (a,b)是否容易(无需重新发明轮子)。我查看Traversable但无法使其正常工作。

4 个答案:

答案 0 :(得分:7)

您也可以使用Bitraversable

[1,4,5]

专门研究

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

答案 1 :(得分:5)

是。仿函数。

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

或者,以无点的方式:

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

此外,正如@Bakuriu所说,如果您已启用TupleSections并导入Control.Applicative,则真的很容易

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

了解详情here

答案 2 :(得分:3)

以下适用于lens

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

答案 3 :(得分:1)

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

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

希望有所帮助。