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

Rafael Cunha de Almeida almeidaraf at gmail.com
Sun Mar 22 19:10:28 EDT 2009


Maurí­cio wrote:
>> 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.
> 
> In one module, you can write:
> 
> ----------
> giveMeFunctions = do {
>     newIORef ...
>     newIORef ...
>     newIORef ...
>     (...)
>     let f1 = ...
>     let f2 = ...
>     return (f1,f2)
> ----------
> 
> and in the main:
> 
> (keyboardMouse,display) <- giveMeFunctions
> 

Doing it like that I could have all the definitions in one module, but
it doesn't solve another important problem: keyboardMouse and display
functions have to have as many parameters as there are IORefs.

In my particular case, since I find out what key the use has pressed
through pattern matching, keyboardMouse has several definitions. So
adding a new IORef means adding a wildcard parameter to each
keyboardMouse definition. As well as a new parameter to the display
function. Which looks a bit clumbersome to me.

In a state-based language I'd have something in the lines of:
	switch (key) {
		case LEFT_KEY :
			/* using var1 ... */
		case RIGHT_KEY :
			/* using var2 ... */
	}
then, handling a new case would be a matter of adding a global
variable and adding a new case in the end of the function containing
the switch.

Whereas in Haskell I would have something like
	keyboard var1 _ LeftKey = ...
	keyboard _ var2 RightKey = ...
If I wanted to add a new IORef I'd have to do something like:
	keyboard var1 _ _ LeftKey = ...
	keyboard _ var2 _ RightKey = ...
	keyboard _ _ var3 RightKey = ...
So, I had to change all previous definitions.


More information about the Haskell-Cafe mailing list