为什么在列表清单中应用“序列”会导致计算其笛卡尔乘积? [英] Why does application of `sequence` on List of Lists lead to computation of its Cartesian Product?
问题描述
我的问题是关于 Prelude
中的序列
函数,其签名如下所示:
sequence:Monad m => [m a] - > m [a]
我明白这个函数对 List
可能
s。例如,在 [Just 3,Just 9]
上应用 sequence 给出
Just [3, 9]
。
我注意到在 List of <
上应用
code> List
s给出它的Cartesian Product。有人可以帮我理解这是怎么发生的?为什么会发生这种情况?
sequence [[1,2],[3,4]]
根据定义,这与以下内容相同:
do x< - [1,2]
y< - [3,4]
return [x,y]
只读它为首先选择1和2之间,然后选择3和4之间的选择。列表monad现在会累积所有可能的结果 - 因此,答案
[[1,3],[1,4],[2,3],[2,4] ]
。
(有关更加混淆的示例,请参阅)
My question is about the
sequence
function inPrelude
, the signature of which is as follows:sequence :: Monad m => [m a] -> m [a]
I understand how this function works for
List
ofMaybe
s. For example, applyingsequence
on[Just 3, Just 9]
givesJust [3, 9]
.I noticed that applying
sequence
onList
ofList
s 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:
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)
这篇关于为什么在列表清单中应用“序列”会导致计算其笛卡尔乘积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!