[Haskell-cafe] Tutorial for using the state monad or a better suggestion?

Brandon S. Allbery KF8NH allbery at ece.cmu.edu
Fri Feb 22 12:11:39 EST 2008

On Feb 22, 2008, at 9:15 , Jefferson Heard wrote:

> Now I'm to the point of making this thing interactive, and I I'm
> trying to figure out the Haskell way of doing this.  Last time I wrote
> a program like this, I made a record data type with all the state and
> placed it into an IORef and curried it into the GLUT callback
> functions.  I'm going to do the same thing now if there aren't cringes
> and wailings from people with a better sense of pure-functional
> aesthetics out there on the list with a willingness to either point me
> towards a tutorial that would help me do this better.  Keep in mind
> that Graphics.UI.GLUT callbacks all want to return an IO (), and thus
> leftover state monads at ends of functions aren't going to be
> acceptable to the standard library...

What I do (with gtk2hs) is visible at http://hpaste.org/3137 ---  
MWPState is a fairly large record.

I will note that this code stores the mutable data in separate  
IORefs, whereas I'm told that it's better to use a single IORef with  
all the mutable state inside it.  (For some reason I had assumed that  
the overhead would be higher.)  That said, the wrappers make it  
fairly easy to refactor it.  Since the IORef(s) and much of the  
remaining state is read-only, I use a ReaderT IO instead of StateT  
IO; this also turned out to be convenient for what turned out to be a  
significant optimization (in response to a timer firing, it collects  
a bunch of data and feeds it into a TreeView, and it turned out to be  
useful to collect it all at the front and use local to roll a  
modified record with the cached values).

(The code in that paste is rather out of date, probably I should  
update it.)

brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery at kf8nh.com
system administrator [openafs,heimdal,too many hats] allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university    KF8NH

More information about the Haskell-Cafe mailing list