Can't understand result of Monad >> application

那年仲夏 提交于 2021-02-08 14:12:13

问题


Operation >> description is the following:

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

Here is the example which confuses me:

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

I'm expecting the list [2,3] which would be result of right part of expression. How can result of [2,3,2,3] be explained?


回答1:


(>>) is by default defined as

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

so the value being ignored is an a in a given monadic value m a. The type of >>= specialised to list is:

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

l >>= f invokes f for each element of the list l to product a list of lists which is then concatenated.

e.g.

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

Ignoring each input element and returning the value [2,3] will result in n copies of the list [2,3] for an input list of length n

e.g.

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

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

this second example is equivalent to ([1] ++ [2]) >> ([2] ++ [3]) in your question.




回答2:


A small complement to the answer by Lee:

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

is equivalent to

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

which is equivalent to

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

which is equivalent to

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

which is close to the imperative pseudocode

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


来源:https://stackoverflow.com/questions/38573331/cant-understand-result-of-monad-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!