[Haskell-cafe] Re: Monads and Functions sequence and sequence_

Ivan Lazar Miljenovic ivan.miljenovic at gmail.com
Sat Oct 30 01:38:32 EDT 2010


On 30 October 2010 16:30, Mark Spezzano <mark.spezzano at chariot.net.au> wrote:
> Not exactly. If you use the type with Maybe Int like so:
>
> sequence [Just 1, Nothing, Just 2]
>
> then the result is Nothing.
>
> Whereas sequence [Just 1, Just 2, Just 3] gives
>
> Just [1, 2, 3]
>
> Why?
>
> I assume there's special implementations of sequence and sequence_ depending on the type of monad used. If it's a sequence_ [putStrLn "hello", putStrLn "goodbye"] then this prints out hello and goodbye on separate lines.
>
> It seems to work differently for different types.

The definition of the monad.  In the Maybe monad, as soon as you get a
Nothing the entire thing returns Nothing.

sequence [ma,mb,mc] = do { a <- ma; b <- mb; c <- mc; return [a,b,c] }
= ma >>= \ a -> mb >>= \ b -> mc >>= \ c -> return [a,b,c]

However, for Maybe:

instance Monad Maybe where
  ...

  Nothing >>= f = Nothing
  Just x >>= f = f x

  ...

So yes, the behaviour of the Monad is dependent upon the Monad.

-- 
Ivan Lazar Miljenovic
Ivan.Miljenovic at gmail.com
IvanMiljenovic.wordpress.com


More information about the Haskell-Cafe mailing list