问题
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