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

后端 未结 3 528
死守一世寂寞
死守一世寂寞 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:38

    sequence acts as if it were defined like this.

    sequence [] = return []
    sequence (m:ms) = do
        x <- m
        xs <- sequence ms
        return (x:xs)
    

    (Or sequence = foldr (liftM2 (:)) (return []) but anyhow…)

    Just think about what happens when applied to a list of lists.

    sequence [] = [[]]
    sequence (list : lists) =
        [ x : xs
        | x <- list
        , xs <- sequence lists
        ]
    

提交回复
热议问题