Skip to content

Instantly share code, notes, and snippets.

@cohei
Last active November 10, 2020 16:03
Show Gist options
  • Save cohei/daad5026cda42173fe8b to your computer and use it in GitHub Desktop.
Save cohei/daad5026cda42173fe8b to your computer and use it in GitHub Desktop.
`catMaybes :: [Maybe a] -> [a]` の一般化
import Data.Foldable (Foldable, toList)
import Data.Functor.Compose (Compose(Compose))
import Data.Tree (Tree(Node))
flatten :: (Foldable f, Foldable g) => f (g a) -> [a]
flatten = toList . Compose
ex1 = [Just 1, Nothing, Just 2]
ex2 = Just [1,2]
ex3 = [[1],[2]]
ex4 = Node Nothing [Node (Just 1) [], Node Nothing [Node (Just 2) []]]
-- >>> flatten ex1
-- [1,2]
-- >>> flatten ex2
-- [1,2]
-- >>> flatten ex3
-- [1,2]
-- >>> flatten ex4
-- [1,2]
@cohei
Copy link
Author

cohei commented Nov 10, 2020

>>> import Control.Lens
>>> toListOf (folded . folded) ex1
[1,2]
>>> :t toListOf (folded . folded)
toListOf (folded . folded)
  :: (Foldable f1, Foldable f2) => f1 (f2 a) -> [a]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment