<div dir="ltr"><div class="gmail_extra"><br><div class="gmail_quote">On Sun, Feb 10, 2013 at 9:17 PM, Brent Yorgey <span dir="ltr"><<a href="mailto:byorgey@seas.upenn.edu" target="_blank">byorgey@seas.upenn.edu</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div class="im">On Sun, Feb 10, 2013 at 02:53:18PM -0800, David Hinkes wrote:<br>
> Hi haskell-beginners,<br>
><br>
> I'm starting to come to the idea of exposing a Monad as a means of<br>
> controlling an API. So, I've started creating my own Monad data types<br>
> based on classical monads. However, I'm running into a problem regarding<br>
> creating monad definitions when using nested Monads.<br>
><br>
> For example:<br>
><br>
> newtype Example m o = Example {<br>
> runExample :: State Int (m o)<br>
> }<br>
><br>
> Is there a clean way to make Example a monad?<br>
<br>
</div>Actually, there isn't! This is one way in which monads turn out to be<br>
*too* powerful: they don't compose very well. If m and n are monads,<br>
then their composition (that is, a type like newtype Composed a =<br>
Composed (m (n a))) is *not* necessarily a monad! So "nesting" monads<br>
in this way is usually not a good idea.<br>
<br>
What you want are called "monad transformers", which give you a way to<br>
"compose" certain monads (though it's more complicated than just<br>
nesting them). You can do your Example type something like this:<br>
<div class="im"><br>
newtype Example m o = Example {<br>
</div> runExample :: StateT Int m o<br>
}<br>
<br>
where StateT is the State monad transformer, defined in the<br>
'transformers' package (and also exported from the 'mtl' package). I<br>
refer you to the typeclassopedia for more information and links to<br>
further reading: <br></blockquote><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<a href="http://www.haskell.org/haskellwiki/Typeclassopedia#Monad_transformers" target="_blank">http://www.haskell.org/haskellwiki/Typeclassopedia#Monad_transformers</a></blockquote><div><br></div><div style>Thanks Brent, I'll try to re-organize around the transforms.<br>
</div></div></div></div>