为什么列出monad按此顺序组合? [英] Why list monad combines in that order?
问题描述
我正在阅读列表单子,并遇到:
I was reading about list monads and encountered:
[1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch)
它产生
[(1,'a'),(1,'b'),(2,'a'),(2,'b')]
这是我的理解方式:
隐含的括号是:
([1,2] >>= \n -> ['a','b']) >>= (\ch -> return (n,ch))
([1,2] >>= \n -> ['a','b'])
应该给出[('a',1),('b',1),('a',2),('b',2)]
因为
instance Monad [] where
return x = [x]
xs >>= f = concat (map f xs) -- this line
fail _ = []
所以concat (map f xs)
是concat (map (\n -> ['a','b']) [1,2])
,应该产生[('a',1),('b',1),('a',2),('b',2)]
-与实际输出完全相反.
so concat (map f xs)
is concat (map (\n -> ['a','b']) [1,2])
which should produce [('a',1),('b',1),('a',2),('b',2)]
- quite the opposite of the actual output.
那我不理解>>= (\ch -> return (n,ch))
部分-我认为这里的n
没有意义.这种特定的推理有缺陷,请您解释一下表达式([1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch)
)是如何逐步计算的?
Then I don't understand >>= (\ch -> return (n,ch))
part - I think that n
here has no sense. That specific reasoning is flawed, could you please explain how that expression([1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch)
) is computed step-by-step?
推荐答案
您的隐式括号是错误的.用这种方式,第一个lambda的n
参数将不在return
的范围内.更像是:
Your implicit parentheses are wrong. The way you have it, the n
parameter to the first lambda would not be in scope in the return
. It is more like:
([1,2] >>= (\n -> ['a','b'] >>= (\ch -> return (n,ch))))
哪个会成为:
concatMap (\n -> concatMap (\ch -> [(n,ch)]) ['a','b']) [1,2]
这篇关于为什么列出monad按此顺序组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!