[Haskell-cafe] How to increment an Int in Haskell (stack overflow
issue)
Daniel Fischer
daniel.is.fischer at web.de
Wed Mar 25 15:51:20 EDT 2009
Am Mittwoch 25 März 2009 20:00:40 schrieb Tim Bauer:
> I have a program that is currently blowing out the stack,
> Stack space overflow: current size 8388608 bytes.
> Use `+RTS -Ksize' to increase it.
> I am pretty sure I get to the end of the computation that
> increments various statistic counters (lazily?)
Far too lazily.
> and only
> when I go to print them out at the end, do things fail.
>
> I have state monad transformer (StateT) that is keeping the
counters
> among other things. The counters are stored in a pair within a larger
> data structure.
>
> > data AState s a = AS { ...
> > asStats :: (Int,Int)
> > ...
> > }
> The problem goes away. But maybe an optimization is covering
> up the crime. So I tried
>
> > incFst (x,y) = (y,x)
> > incSnd (x,y) = (y,x)
>
> And indeed this again crashes. Any hints as to what is going on?
>
> If it is relevant, here is my code to access the counter within
> the state monad
>
> > countFst :: StateT (AState s a) IO ()
> > countFst = modify $ \as -> as{asStats = incFst (asStats as)}
This is where the strictness you added to incFst is hidden again.
countFst writes the thunk (\as -> as{asStats = incFst (asStats as)}) to
the state, incFst isn't even called yet.
To force the evaluation,
a) make the stats two strict (!Int) fields
b) evaluate the state, like in
countFst = do
as <- get
let a = asStats1 as
as1 = as{asStats1 = a+1}
put $! as1
>
> and the monad transformer I am using is
>
> > import Control.Monad.State.Strict
More information about the Haskell-Cafe
mailing list