Search code examples
haskellmonads

How to get from a list of a Monad to a Monad of a list


I am looking for a way to convert a type of [m [a]] to m [[a]] where m is a Monad of some type.


Solution

  • You're looking for Control.Monad.sequence

    λ> import Control.Monad (sequence)
    
    λ> sequence [Just [1,2,3], Just [4,5,6], Just [7,8,9]]
    Just [[1,2,3],[4,5,6],[7,8,9]]
    

    Its type is (Traversable t, Monad m) => t (m a) -> m (t a).
    Specialising t to [] and a to [a], we get

    sequence :: [m [a]] -> m [[a]]