[Haskell-beginners] State Monad in constant space?

David McBride toad3k at gmail.com
Tue Jun 14 15:27:08 UTC 2016


Remember that StateT (and by extension, State) is just a newtype wrapper.
Newtypes have no runtime cost.  In this case it simply contains a
function.  Constructing an expression full of binds against StateT before
supplying an argument via runStateT is no different than combining several
functions and supplying their argument later.

As far as memory usage is concerned, there is one caveat.  The state
variable that is returned after every bind can build up thunks if it is
altered but not fully evaluated in any given step.  This could lead to a
memory link as operations are tacked onto the state variable you supplied.
If you use Control.Monad.State.Strict, that variable will be evaluated
whether you use it or not, preventing laziness from building up thunks.

On Sun, Jun 12, 2016 at 5:11 PM, martin <martin.drautzburg at web.de> wrote:

> Hello all,
>
> the State Monad wraps around a computation s -> (s,a). Inside a do block I
> am actually assembling such a computation.
> Now when I do this many times, i.e. in a recursice call, I am builing a
> huge expression
>
>         m a >>= (\a -> mb) >>= (\b -> mc) ...
>
> The result of this expression is a function s -> (s,a). But I cannot see
> how the space for this expression can be
> reclaimed, and how it could ever run in constant space. Once I call
> runState and I provide an initial s, I have some
> hope, but before?
>
> How is this supposed to work? How do I avoid allocating space for this
> huge expression?
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20160614/f0499655/attachment.html>


More information about the Beginners mailing list