所以我试图准确理解Haskell >>=
符号是如何工作的。
我知道它与monad一起使用,并且它基本上扩展(因为它实际上是语法糖)到与bind(>>
)或then(Prelude> do [1, 2, 3]; "hello"
)相关联的匿名函数中,如此处所示{{3 }}
然而我的问题为什么以下命令
"hellohellohello"
返回
{
global: {
userhtml: 'your html code in a string'
}
}
我知道数组实际上是monad(并且这些字符串是字符数组)但是我没有看到这会导致上述行为。
答案 0 :(得分:18)
do [1, 2, 3]; "hello"
desugars to
[1, 2, 3] >> "hello"
与
相同[1, 2, 3] >>= (\_ -> "hello")
与
相同concatMap (\_ -> "hello") [1, 2, 3]
与
相同concat (map (\_ -> "hello") [1, 2, 3])
与
相同concat [(\_ -> "hello") 1, (\_ -> "hello") 2, (\_ -> "hello") 3])
与
相同concat ["hello","hello","hello"]
与
相同"hellohellohello"
答案 1 :(得分:3)
为了补充约阿希姆·布莱特纳的回答,从另一个角度看这个:
do [1, 2, 3]
"hello"
是
do a <- [1, 2, 3]
b <- "hello"
return b
是
do a <- [1, 2, 3]
do b <- "hello"
do return b
是
[b | a <- [1,2,3], b <- "hello"]
与伪代码
相同for a in (a list of Nums) [1, 2, 3]:
-- here we have `a` (a Num)
for b in (a list of Chars) "hello":
-- here we have that same `a` (a Num),
-- and `b` (which is a Char)
emit b -- whatever "emit" means
当然,列表(不是&#34;数组&#34;) stuff 的列表理解(无论那些东西是什么,比如Nums,Chars等。 )desugar到相同的concatMap
- 使用代码;但它有时更容易在心理上处理它们,或者作为一些嵌套循环的规范。
事实上,do
- 符号似乎很容易成为for
- 符号。