Why does application of `sequence` on List of Lists lead to computation of its Cartesian Product?

后端 未结 3 527
死守一世寂寞
死守一世寂寞 2020-12-24 11:58

My question is about the sequence function in Prelude, the signature of which is as follows:

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


        
3条回答
  •  余生分开走
    2020-12-24 12:23

    This works because using lists as monads in Haskell makes them model indeterminism. Consider:

    sequence [[1,2],[3,4]]
    

    By definition this is the same as:

    do x <- [1,2]
       y <- [3,4]
       return [x,y]
    

    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)

提交回复
热议问题