My question is about the sequence function in Prelude, the signature of which is as follows:
sequence :: Monad m => [m a] -> m [a]
I understand how this function works for List of Maybes. For example, applying sequence on [Just 3, Just 9] gives Just [3, 9].
I noticed that applying sequence on List of Lists gives its Cartesian Product. Can someone please help me understand how/why this happens?
This works because using lists as monads in Haskell makes them model indeterminism. Consider:
By definition this is the same as:
Just read it as “First a choice between 1 and 2, then a choice between 3 and 4”. The list monad will now accumulate all possible outcomes – hence the answer
[[1,3],[1,4],[2,3],[2,4]].(for an even more obfuscated example, see here)