翻转可能和列表

时间:2015-03-05 18:51:02

标签: haskell

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

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

我认为它不一定是MaybeList,而是Functor ApplicativeMonad,但我可以'想一想。

1 个答案:

答案 0 :(得分:10)

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

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

The top few Hoogle 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以外的类型。