无法理解 Monad >> 应用程序的结果

Can't understand result of Monad >> application

操作>>描述如下:

Sequentially compose two actions, discarding any value produced by the first, like sequencing operators (such as the semicolon) in imperative languages.

这是让我感到困惑的例子:

> ([1] ++ [2]) >> ([2] ++ [3])
[2,3,2,3]

我期待列表 [2,3],这将是表达式右侧部分的结果。如何解释 [2,3,2,3] 的结果?

(>>) 默认定义为

a >> b = a >>= (\_ -> b)

因此被忽略的值是给定单值 m a 中的 a>>= 专门用于列表的类型是:

(>>=) :: [a] -> (a -> [b]) -> [b]

l >>= f 为列表 l 的每个元素调用 f 以生成一个列表列表,然后将其连接起来。

例如

[1,2] >>= (\i -> [i, -i])
> [1,-1,2,-2]

忽略每个输入元素并返回值 [2,3] 将导致长度为 n

的输入列表的 n 个副本 [2,3]

例如

[1] >>= (\_ -> [2,3])
> [2,3]

[1,2] >>= (\_ -> [2,3])
> [2,3,2,3]

第二个例子相当于你问题中的 ([1] ++ [2]) >> ([2] ++ [3])

李的回答的小补充:

([1] ++ [2]) >> ([2] ++ [3])

相当于

([1] ++ [2]) >> ([2] ++ [3]) >>= \x -> return x

相当于

([1] ++ [2]) >>= \y -> ([2] ++ [3]) >>= \x -> return x

相当于

[ x | y <- [1]++[2] , x <- [2]++[3] ]

接近命令式伪代码

for y in [1]++[2]:
   for x in [2]++[3]:
      print x