Last active
January 9, 2017 06:29
-
-
Save tonymorris/14fd38dedb6a648cdd03c156099d9c22 to your computer and use it in GitHub Desktop.
Generalised catMaybes/mapMaybe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Lens | |
import Data.Monoid | |
newtype Compose f g a = | |
Compose (f (g a)) | |
instance (Foldable f, Foldable g) => Foldable (Compose f g) where | |
foldr f z (Compose x) = | |
foldr (\a b -> foldr f b a) z x | |
collapse0 :: | |
(Cons r r a a, AsEmpty r) => | |
Getting (Endo r) s a | |
-> s | |
-> r | |
collapse0 x = | |
foldrOf x cons (_Empty # ()) | |
collapse1 :: | |
(Cons r r a a, AsEmpty r) => | |
Getting (Endo r) (Compose f g b) a | |
-> f (g b) | |
-> r | |
collapse1 x = | |
collapse0 x . Compose | |
collapse2 :: | |
(Cons r r a a, AsEmpty r) => | |
Getting (Endo r) (Compose (Compose f g) h b) a | |
-> f (g (h b)) | |
-> r | |
collapse2 x = | |
collapse1 x . Compose | |
map1 :: | |
(Cons r r a a, AsEmpty r, Functor f) => | |
Getting (Endo r) (f c) a | |
-> (b -> c) | |
-> f b | |
-> r | |
map1 x f = | |
collapse0 x . fmap f | |
map2 :: | |
(Cons r r a a, AsEmpty r, Functor f) => | |
Getting (Endo r) (Compose f g c) a | |
-> (b -> g c) | |
-> f b | |
-> r | |
map2 x f = | |
collapse1 x . fmap f | |
map3 :: | |
(Cons r r a a, AsEmpty r, Functor f) => | |
Getting (Endo r) (Compose (Compose f g) h c) a | |
-> (b -> g (h c)) | |
-> f b | |
-> r | |
map3 x f = | |
collapse2 x . fmap f | |
---- | |
mapMaybe :: | |
(a -> Maybe b) | |
-> [a] | |
-> [b] | |
mapMaybe = | |
map2 folded | |
catMaybes :: | |
[Maybe a] | |
-> [a] | |
catMaybes = | |
collapse1 folded | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment