我正在尋找可以同時映射和展平列表和Maybes的代碼。我在this topic發現了這樣的flatMap功能:flatmap列表和Maybes
flatMap :: (t -> [a]) -> [t] -> [a]
flatMap _ [] = []
flatMap f (x:xs) = f x ++ flatMap f xs
這工作得很好:
> flatMap id [[],[1,2],[3],[],[4,5,6]]
[1,2,3,4,5,6]
唯一的問題是,它並不適用於Maybes作品。相反,我必須使用Data.Maybe.mapMaybe
:
> Data.Maybe.mapMaybe id [Just 1, Nothing, Just 2, Just 3, Nothing]
[1,2,3]
是否有一個內置的功能,可以同時處理列表和Maybes(也許一些其他類型的)?
當你知道你有什麼,你可以使用['catMaybes :: [也許] - > [A]']( http://www.haskell.org/hoogle/?hoogle=catMaybes)或['concat :: [[a]] - > [a]'](http://www.haskell.org/hoogle/?hoogle = concat)與['map ::(a - > b) - > [a] - > [b]'](http://www.haskell.org/hoogle/?hoogle=map)。 – rampion 2012-02-28 14:59:57
Or = <<,列表版本 – 2012-02-29 04:16:23