[Haskell-cafe] Sometimes I wish there was a global variable

Jake McArthur jake at pikewerks.com
Mon Mar 23 11:34:01 EDT 2009


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Rafael Cunha de Almeida wrote:
| Hello,
|
| I am writing a OpenGL program in haskell, it can be found in:
| 	http://github.com/aflag/galo/tree/master
| But I hope this e-mail will be self-contained :).
|
| My main function goes like this:
|     (...)
|     rotX <- newIORef (0.0::GLfloat)
|     rotY <- newIORef (0.0::GLfloat)
|     pos <- newIORef (0.0::GLfloat, 0.0, 0.0)
|
|     displayCallback $= display (map f range) rotX rotY pos
|
|     keyboardMouseCallback $= Just (keyboardMouse rotX rotY pos)
|     (...)
|
| Notice that rotX, rotY and pos are meant to be used as comunication
| between the keyboardMouse and display functions. They need to be set as
| 0 first, so display won't do anything. Only when they user press a few
| buttons that those values change, so display behaves accordanly.
|
| In a state-based language I would place display and keyboardMouse in one
| module and let them communcate to each other like they want. In haskell,
| I'm not quite sure how to do it except by that parameter passing style.
|
| I thought about how state-monad may help with that. But I'm not sure how
| I'd make the state variable to be contained inside a
| display/keyboardMouse module.

Another way to do this would be something like this:

~    main = do
~      ...
~      displayCallback $= initialDisplayFunction
~      keyboardMouseCallback $= keyboardMouseFunction
~      ...

~    keyboardMouseFunction = do
~      rotX <- ...
~      rotY <- ...
~      pos <- ...
~      ...
~      displayCallback $= display ... rotX rotY rotZ

You could even write your own state monad that does this callback
reassignment for you (perhaps by wrapping StateT s IO a), then you can
forget about all this explicit parameter passing.

- - Jake
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAknHq+kACgkQye5hVyvIUKnX3ACeMLD8FLOTEya8can6veyp6cT3
ClMAnRdfl/DyOshvzlBF8QCtYgTf87fd
=Bp4F
-----END PGP SIGNATURE-----


More information about the Haskell-Cafe mailing list