Simple monads

Derek Elkins ddarius@hotpop.com
Thu, 26 Jun 2003 17:57:43 -0400


On Thu, 26 Jun 2003 14:40:51 -0400 (EDT)
Mark Carroll <mark@chaos.x-philes.com> wrote:

> Not really seeing why Unique is in the IO monad, 

What Unique?  The one in the GHC source?  If so, it seems that it's so
you can create multiple unique supplies that don't overlap. Since the
unique supply isn't a monad transformer or over IO computations, you
couldn't simply stay in one UniqueSupply computation for the whole
program.  Anyways, it's only creation that is in the IO monad.

> not deeply
> understanding the use of Haskell extensions in the State source, 

I'm assuming Control.Monad.State's source in which case -no- extensions
are used for -State- (well, at least I don't see any quickly glancing). 
Extensions are used for the -MonadState class-.  For the MonadState
class they are pretty much necessary.  Multiparameter type classes are
necessary because the state type depends on the monad (get would have
type forall s.Monad m => m -> s otherwise which is rather meaningless),
the function dependencies tell the type checker that the state type is
completely determined by the monad type.

> and
> wanting to try to learn a bit more about monads, 

I'm not a big supporter of reading (arbitrary) sourcecode to learn
a language (at least early on).  It isn't aimed at being didactic, there
are compromises/irrelevant details/added complexities/hidden
assumptions, even if it's well-documented the documentation is still
going to assume the reader has a certain level of competence and is not
going to document the why or how of day to day things (e.g. accumulating
parameters), and finally it may simply be a poor (or at least not
polished) example of coding.

> I thought I'd try to
> write my own monad for the first time: something for producing a
> series of unique labels. This is how it turned out:
> 
> =====================================================================
> ===== module Label (Label, Labeller, newLabel)
> where
> import Monad
> 
> newtype Label = Label Int deriving (Eq, Ord)

why not Show as well?

> (a) People could point out to me where I'm still confused, as revealed
> by my code. Is it needlessly complicated?

It could hardly be made simpler, well except for simply wrapping State
with appropriate functions/types ;).  You may want to watch out for
laziness though, e.g. last $ sequence $ replicate 1000 newLabel is Label
(1+1+1+1+1+1+1+1+1+...minBound) as opposed to Label (999+minBound) (I'm
pretty sure, well modulo what the compiler might do).  The simplest fix
would be making Int a strict field (adding ! to it) or changing newLabel
to n `seq` (n+1,Label n).