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.<div>I didn&#39;t find anything that does this on hackage so I implemented a small wrapper around STRefs which does what I want.</div>
<div><br></div><div>Before I put it on hackage I thought I&#39;d run it by haskell-cafe.</div><div><br></div><div>It works as follows:</div><div><div><div><div><br></div><div><div>test :: (String, Bool)</div><div>test = runContext $ do</div>
<div>  a &lt;- newRef &quot;foo&quot;</div><div>  b &lt;- newRef False</div><div>  restore &lt;- save</div><div>  writeRef a &quot;bar&quot;</div><div>  writeRef b True</div><div>  when someCondition restore</div><div>  x &lt;- readRef a</div>
<div>  y &lt;- readRef b</div><div>  return (x, y)</div><div><br></div><div><br></div><div>If someCondition, the existing state is restored and test returns (&quot;foo&quot;, False)</div><div>  otherwise nothing special happens and test returns (&quot;bar&quot;, True)</div>
<div><br></div><div>Also each reference has a unique key that can make it much easier to convert structures that use STRefs to pure stuctures.</div><div><br></div><div>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.</div>
<div><br></div><div><div>My implementation is here:</div><div><a href="http://gist.github.com/316738">http://gist.github.com/316738</a></div><div><br></div><div><br></div></div><div><br></div><div>What do you think? Any suggestions?</div>
<div>Does anything like this already exist in hackage?</div><div>Does this seem useful to other people besides me? :)</div><div>Any glaring purity issues that I overlooked?</div><div><br></div><div><div><div><br></div><div>
Thanks for your input,</div><div><br></div><div>- Job</div><div><br></div></div></div></div></div></div></div>