Is there some reason why the Prelude doesn’t define the list monad like this? (Note the non-standard implementation of >>.)
instance Monad [] where
m >>= k = concat (map k m)
m >> k = k -- a.k.a. flip const
return x = [x]
fail s = []
I tried checking this against the monad laws, but they don’t mention >>. The Monad class definition is this:
m >> k = m >>= \_ -> k
which in the [] instance would translate to this:
concat (map (\_ -> k) m)
which is of course not equivalent to flip const—they produce an obviously different results for, say, [1..5] >> return 1. But it’s not clear to me whether this default definition is a law that instances of Monad must respect, or just a default implementation that satisfies some other law that the flip const implementation would also satisfy.
Intuitively, given the intent of the list monad (“nondeterministic computations”), it seems like the alternative definition of >> would be just as good, if not better thanks to pruning branches that are guaranteed to be equal down to just one. Or another way of saying this is that if we were dealing with sets instead of lists, the two candidate definitions would be equivalent. But am I missing some subtlety here that makes the flip const definition wrong for lists?
EDIT: ehird’s answer catches a very obvious flaw with the above, which is that it gets the wrong intended result for [] >> k, which should be [], not k. Still, I think the question can be amended to this definition:
[] >> k = []
_ >> k = k
a >> bmust always be equivalent toa >>= const b; it’s only in theMonadclass so that you can define a more efficient (but semantically equivalent) version. That’s why it’s not part of the monad laws: it’s not really part of the definition of a monad, only the typeclass (likefail).Unfortunately, I can’t find anywhere in the documentation for the base package where this is stated explicitly, but I think older versions may have defined
(>>)outside of theMonadtypeclass.For what it’s worth, your definition of
(>>)breaks the list monad’s use for nondeterministic computations. Since[]is used to represent failure,[] >> mmust always be[]; you can’t continue on after you’ve exhausted all possible branches! It would also mean that these two programs:could differ in behaviour, since the former desugars with
(>>)and the latter with(>>=). (See the Haskell 2010 Report.)