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

Daniel Peebles pumpkingod at gmail.com
Sat Oct 30 01:41:33 EDT 2010


That is a result of the implementation of the specific Monad instance, and
that does depend on the type, as you say (but it isn't determined for
sequence(_) specifically).

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

is why a Nothing "pollutes" the sequenced lists of Maybes. If Maybe is a
Monad representing computations that can fail (to produce a result), then if
you sequence a bunch of such computations together, if any one computation
fails, your entire computation fails. This reflects the natural behavior of
the Maybe monad, where if you use "x <- maybe computation", the only way to
produce that x is if the computation returned Just.

In other monads, sequence will behave in the "right way" for that monad.

On Sat, Oct 30, 2010 at 1:30 AM, 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.
>
> Mark
>
>
> On 30/10/2010, at 3:42 PM, Bardur Arantsson wrote:
>
> > On 2010-10-30 07:07, Mark Spezzano wrote:
> >> Hi,
> >>
> >> Can somebody please explain exactly how the monad functions "sequence"
> and "sequence_" are meant to work?
> >>
> >> I have almost every Haskell textbook, but there's surprisingly little
> information in them about the two functions.
> >>
> >> From what I can gather, "sequence" and "sequence_" behave differently
> depending on the types of the Monads that they are processing. Is this
> correct? Some concrete examples would be really helpful.
> >>
> >
> > sequence [m1,m2,m3,m4,...] = do
> >  x1 <- m1
> >  x2 <- m2
> >  x3 <- m3
> >  x4 <- m4
> >  ...
> >  return [x1,x2,x3,x4,...]
> >
> > sequence_ [m1,m2,m3,m4,...] = do
> >  m1
> >  m2
> >  m3
> >  m4
> >  ...
> >  return ()
> >
> > Cheers,
> >
> > _______________________________________________
> > Haskell-Cafe mailing list
> > Haskell-Cafe at haskell.org
> > http://www.haskell.org/mailman/listinfo/haskell-cafe
> >
> >
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20101030/252f3e7a/attachment.html


More information about the Haskell-Cafe mailing list