returning an element extracted from a monad; redundant?
Asked Answered
C

2

6

Are the following two implementations of flatten equivalent for all well-behaved Monads?

flatten1 xss = do
    xs <- xss
    x <- xs
    return x

flatten2 xss = do
    xs <- xss
    xs
Cab answered 20/6, 2013 at 15:35 Comment(2)
Yup, 100% identical. You could just import Control.Monad and write join, or use xss >>= id.Portwine
Yes. do { ...; x <- m; return x } is always equal to do { ...; m }.Aldwon
H
9

Yes, they're identical. They're desugared as

flatten1 xss =
    xss >>= \xs -> xs >>= \x -> return x

flatten2 xss = do
    xss >>= \xs -> xs

The first one is equivalent to

xss >>= \xs -> xs >>= return

and by the Right identity monad law equivalent to

xss >>= \xs -> xs
Hehre answered 20/6, 2013 at 15:54 Comment(0)
O
5

In short, yes. To prove it:

You've written:

xss >>= (\xs -> xs >>= \x -> return x)
xss >>= (\xs -> xs >>= return) -- eta

in the first and

xss >>= (\xs -> xs)
xss >>= id

according to the monad laws, return is a right identity so that

m >>= return === m

so we can do

xss >>= (\ xs -> xs >>= return )
xss >>= (\ xs -> xs )
xss >>= id
Olatha answered 20/6, 2013 at 15:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.