为什么列出monad按此顺序组合? [英] Why list monad combines in that order?

查看:78
本文介绍了为什么列出monad按此顺序组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读列表单子,并​​遇到:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆