Search code examples
haskellmonadsdo-notation

returning an element extracted from a monad; redundant?


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

Solution

  • 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