The strict state monad is defined using:
m >>= k = State $ \s ->
case runState m s of
(a, s') -> runState (k a) s'
But this can still leak memory, because a
and s'
are left unevaluated. For example, we might have a function f
that takes a large object as input and quickly returns (a, s')
, but as long as a
is left unevaluated the input to f
cannot be GC'ed.
One potential solution is to have f
return seq a (a, s')
, but this isn't always possible if we are using something like MonadRandom
, and the state is encapsulated away from f
. Is there a version that is defined like this:
m >>= k = State $ \s ->
case runState m s of
(!a, !s') -> runState (k a) s'
Does this exist in a library anywhere already?