Unable to understand the result of using Monad >>

The operation → description is as follows:

Consecutively create two actions, discarding any value created in the first place, like sequence operators (for example, semicolons) languages.

Here is an example that bothers me:

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

I expect a list [2,3] that will be the result of the correct part of the expression. How to explain the result [2,3,2,3]?

+6
source share
2 answers

(>>) the default is defined as

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

therefore, the ignored value is a in the given monadic value ma . Type >>= , specialized for displaying:

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

l >>= f calls f for each element of the list l to display a list of lists, which is then concatenated.

eg.

 [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

eg.

 [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.

+12
source

A small addition to Lee's answer:

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

equivalently

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

which is equivalent

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

which is equivalent

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

which is close to imperative pseudocode

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

All Articles