I\'m trying to make a toy application, just to get my head around how to write event driven programs in Haskell. What I\'m trying to do is draw a line to a canvas which moves fo
First off, you could have a global. Ignoring that solution as bad form, this looks like a job for an MVar. In main
you just make a new MVar which you can update in onKeyboard
and check in myDraw
:
...
import Control.Concurrent.MVar
main = do
...
mv <- newMVar 0
....
canvas `on` exposeEvent $ do liftIO $ renderWithDrawable draWin (myDraw mv 10)
...
window `on` keyPressEvent $ onKeyboard canvas mv
onKeyboard canvas mv = do
modifyMVar_ mv (\x -> return (x + 1))
....
myDraw mv pos = do
val <- readMVar mv
...
Note that sharing mutable state is also often useful when passing functions as arguments by first using partial application to provide the MVar
(or TVar
, IORef
, whatever).
Oh, and a warning: MVars aren't strict - if the application has the potential to write lots without forcing the value (i.e. reading and comparing the contained Int
), then you should force the value before writing to avoid building a huge thunk.