Unsequence Monad function within Haskell

You can’t have an unsequence :: (Monad m) => m [a] -> [m a]. The problem lies with lists: you can’t be sure how may elements you are going to get with a list, and that complicates any reasonable definition of unsequence.

Interestingly, if you were absolutely, 100% sure that the list inside the monad is infinite, you could write something like:

unsequenceInfinite :: (Monad m) => m [a] -> [m a]
unsequenceInfinite x = fmap head x : unsequenceInfinite (fmap tail x)

And it would work!

Also imagine that we have a Pair functor lying around. We can write unsequencePair as

unsequencePair :: (Monad m) => m (Pair a) -> Pair (m a)
unsequencePair x = Pair (fmap firstPairElement x) (fmap secondPairElement x)

In general, it turns out you can only define unsequence for functors with the property that you can always “zip” together two values without losing information. Infinite lists (in Haskell, one possible type for them is Cofree Identity) are an example. The Pair functor is another. But not conventional lists, or functors like Maybe or Either.

In the distributive package, there is a typeclass called Distributive that encapsulates this property. Your unsequence is called distribute there.

Leave a Comment