[Haskell-cafe] save/restore of STRef state

Andrew Coppin andrewcoppin at btinternet.com
Sat Feb 27 11:53:04 EST 2010


Job Vranish wrote:
> I was using STRefs the other day and I ran across a case where I 
> really wanted the ability to save the state of all my references, 
> execute some action, and then restore the state later if needed.
> I didn't find anything that does this on hackage so I implemented a 
> small wrapper around STRefs which does what I want.

If you use something like the State or Reader monad, it becomes trivial 
to temporarily modify the carried state. But maybe something like this 
is occasionally useful. (In particular, it seems to allow you to restore 
to a point not necessarily matching the most recent save.)

> What do you think? Any suggestions?

Deriving the Eq instance for ContextRef means that it will compare the 
key *and* the IORef. Which gives the right answer, but seems rather 
redundant. Comparing the key alone should be sufficient.

> Any glaring purity issues that I overlooked?

Why an IORef? Why not an STRef? Then you won't need unsafeIOToST. (And 
since the type system forces a ContextRef to exist in only one state 
thread, worrying about thread isolation with atomicModifyIORef seems 
unecessary.)

Using a state monad with a mutable structure as the state looks highly 
dubious. (The whole point of a state monad is, after all, to avoid 
needing to mutate stuff.) I can see 2 calls to "get", but none to "put". 
I would suggest you either use a reader monad with mutable state, or a 
state monad with immutable state. One or the other. (Personally, I'd go 
for the latter.)

I'm also not 100% sure how the saving and restoring part works. Map Int 
(IO (IO ())) sounds fruity though.



More information about the Haskell-Cafe mailing list