什么是将
List (Maybe a)
转换为 Maybe (List a)
的好方法?逻辑很简单:如果所有项都是 Just a
,则返回 Just (List a)
,否则返回 Nothing
。Example 1:
input: [ Just 1, Just 2, Just 3 ]
output: Just [ 1, 2, 3 ]
Example 2:
input: [ Just 1, Nothing, Just 3 ]
output: Nothing
有没有一些内置函数可以轻松地完成这个任务?
我想到的最好方法看起来像这样:
listOfMaybesToMaybeList : List (Maybe a) -> Maybe (List a)
listOfMaybesToMaybeList listOfMaybes =
List.foldl
(\maybeItem ->
\maybeResultList ->
case ( maybeItem, maybeResultList ) of
( Just item, Just resultList ) ->
Just (List.append resultList [ item ])
( _, _ ) ->
Nothing
)
(Just [])
listOfMaybes
这种函数应该取什么名字比较合适?我搜索了一下,发现 Haskell 里有一个叫做 sequence
的函数似乎做了类似的事情。