[Haskell-cafe] save/restore of STRef state

Job Vranish job.vranish at gmail.com
Sat Feb 27 11:17:34 EST 2010


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.

Before I put it on hackage I thought I'd run it by haskell-cafe.

It works as follows:

test :: (String, Bool)
test = runContext $ do
  a <- newRef "foo"
  b <- newRef False
  restore <- save
  writeRef a "bar"
  writeRef b True
  when someCondition restore
  x <- readRef a
  y <- readRef b
  return (x, y)


If someCondition, the existing state is restored and test returns ("foo",
False)
  otherwise nothing special happens and test returns ("bar", True)

Also each reference has a unique key that can make it much easier to
convert structures that use STRefs to pure stuctures.

Reads, writes and creating refs are still constant time operations (with
only a very very small overhead) and garbage collecting behavior should be
the same as with regular STRefs.

My implementation is here:
http://gist.github.com/316738



What do you think? Any suggestions?
Does anything like this already exist in hackage?
Does this seem useful to other people besides me? :)
Any glaring purity issues that I overlooked?


Thanks for your input,

- Job
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20100227/820b7abb/attachment.html


More information about the Haskell-Cafe mailing list