Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't understand result of Monad >> application

Tags:

haskell

monads

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?

like image 487
Scipio Avatar asked Jul 25 '16 16:07

Scipio


2 Answers

(>>) 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.

like image 134
Lee Avatar answered Sep 19 '22 12:09

Lee


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
like image 20
chi Avatar answered Sep 21 '22 12:09

chi