[Haskell-cafe] Stacking StateTs

wren ng thornton wren at freegeek.org
Mon Feb 23 18:31:30 EST 2009


Luis O'Shea wrote:
> One way to do this is to stack two StateTs on top of m.

Another way, what might be easier to reason about, is to crush those two 
layers together and use a tuple for the state:

     StateT s1 (StateT s2 m) a == StateT (s1,s2) m a

Then the only thing you'll have to worry about is making sure the 
different "clients" only access s1 or s2 as appropriate.

One approach to access control is to make a newtype S = (s1,s2) and 
define a typeclass taking S and returning the different projections of 
it (e.g. s1 or s2). This way if you needed to add another StateT layer 
you can just adjust the definition of S and add a new typeclass 
instance. Similarly if you wanted to rearrange the contents of S.

This also works if you want to have different S, S', etc ---even if they 
share projections--- though you'll need to use MPTCs (or similar) so you 
can overload on the total state as well as the projections.

The downside to the typeclass approach is that you can't have two 
projections (of the same S) sM and sN which are the same type. If you 
want that you'll need to newtype one of the projections, manually pass 
around the projector dictionaries, or similar.

-- 
Live well,
~wren


More information about the Haskell-Cafe mailing list