Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flip Maybe and List

Tags:

haskell

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.

like image 910
Ryoichiro Oka Avatar asked Dec 24 '22 22:12

Ryoichiro Oka


1 Answers

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 top few Hoogle 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.

like image 188
Tikhon Jelvis Avatar answered Jan 02 '23 06:01

Tikhon Jelvis