List monad如何在这个例子中工作? [英] How does the List monad work in this example?
问题描述
List monad包含 return x = [x]
。那么为什么在下面的例子中结果不是 [([a,b],[2,3])]
?
>配对b = do {x < - a; y< -b; return(x,y)}
>对[a,b] [2,3]
[(a,2),(a,3),(b,2),(b,3 )]
让我们先分析并重写函数< code $> $ :
pairs ab = do {x < - a; y< -b; return(x,y)}
这里我们有一个monad。我们使用 do
作为语法糖。但编译器会将其重写为:
pairs ab = a>> =(\ x - > b> > =(\y-> return(x,y)))
更多规范形式:
pairs ab =(>> =)a(\ x - >(>> ; =)b(\y-> return(x,y)))
list monad的定义如下:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ >> =)xs f = concatMap f xs
所以我们写道:
$ b $
pairs ab = concatMap(\ x - > concatMap(\ y - > [(x,y)])b)a
因此,我们将两个列表 a
和 b
,我们在 a
上执行 concatMap
使用函数(\ x - > concatMap(\y - > [(x,y)])b)
。在那个函数中,我们用 b
执行另一个 concatMap
因此,如果我们用对[[a,b]来评估这个值,那么[b,b,b] ] [2,3]
我们得到:
pairs [a,b ] [2,3]
- > concatMap(\ x - > concatMap(\ y - > [(x,y)])[2,3])[a,b]
- > concatMap(\y-> [(a,y)])[2,3] ++ concatMap(\y-> [(b,y)])[2,3]
- > [(a,2)] ++ [(a,3)] ++ [(b,2)] ++ [(b,3)]
- > [(a,2),(a,3),(b,2),(b,3)]
The List monad has return x = [x]
. So why in the following example is the result not [(["a", "b"], [2, 3])]
?
> pairs a b = do { x <- a; y <- b; return (x, y)}
> pairs ["a", "b"] [2,3]
[("a",2),("a",3),("b",2),("b",3)]
Let us first analyze and rewrite the function pairs
:
pairs a b = do { x <- a; y <- b; return (x, y)}
Here we thus have a monad. We use do
as syntactical sugar. But the compiler rewrites this to:
pairs a b = a >>= (\x -> b >>= (\y -> return (x, y)))
Or in a more canonical form:
pairs a b = (>>=) a (\x -> (>>=) b (\y -> return (x, y)))
Now the list monad is defined as:
instance Monad [] where
return x = [x]
(>>=) xs f = concatMap f xs
So we have written:
pairs a b = concatMap (\x -> concatMap (\y -> [(x, y)]) b) a
So we thus take as input two lists a
and b
, and we perform a concatMap
on a
with as function (\x -> concatMap (\y -> [(x, y)]) b)
. In that function we perform another concatMap
on b
with as function \y -> [(x, y)]
.
So if we evaluate this with pairs ["a", "b"] [2,3]
we get:
pairs ["a", "b"] [2,3]
-> concatMap (\x -> concatMap (\y -> [(x, y)]) [2,3]) ["a", "b"]
-> concatMap (\y -> [("a", y)]) [2,3] ++ concatMap (\y -> [("b", y)]) [2,3]
-> [("a", 2)] ++ [("a", 3)] ++ [("b", 2)] ++ [("b", 3)]
-> [("a", 2), ("a", 3), ("b", 2), ("b", 3)]
这篇关于List monad如何在这个例子中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!