I want a function that takes in a list of Maybe a, and returns Just [a] if all contents are Just a, otherwise returns Nothing.
f :: [Maybe a] -> Maybe [a]
-- f [Just x, Just y ] = Just [x, y]
-- f [Just x, Nothing] = Nothing
I think it doesn't have to be Maybe and List but any Functor Applicative or Monad, but I can't think up the way.
This is a great example of where hoogle comes in handy. It's a search engine where you can enter a type signature and get the functions that match—even if they are more polymorphic.
Entering [Maybe a] -> Maybe [a] we get a bunch of results.

The first one is:
sequence :: Monad m => [m a] -> m [a]
We can try this out in 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
Hey, look at that: exactly what we were looking for! So the function you want is sequence which also happens to work for types other than Maybe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With