翻转可能和列表

Flip Maybe and List

我想要一个接受 Maybe a 列表的函数,如果所有内容都是 Just a,则 returns Just [a],否则 returns Nothing

f :: [Maybe a] -> Maybe [a]
-- f [Just x, Just y ] = Just [x, y]
-- f [Just x, Nothing] = Nothing

我认为不一定是 MaybeList,而是任何 Functor ApplicativeMonad,但我想不出来一路走来。

这是 hoogle 派上用场的一个很好的例子。它是一个搜索引擎,您可以在其中输入类型签名并获得匹配的函数——即使它们具有更多的多态性。

输入 [Maybe a] -> Maybe [a] 我们得到 a bunch of results.

第一个是:

sequence :: Monad m => [m a] -> m [a]

我们可以在 GHCi 中尝试一下:

Prelude> let xs = [Just 1, Just 2, Just 3]
Prelude> sequence xs
Just [1,2,3]
Prelude> let xs = [Just 1, Nothing, Just 3]
Prelude> sequence xs
Nothing

嘿,看看那个:正是我们要找的!所以你想要的功能是 sequence 它也适用于 Maybe.

以外的类型