[Haskell-cafe] How to variables

robert dockins robdockins at fastmail.fm
Mon Jul 18 14:14:43 EDT 2005



yin wrote:
> Hello all!
> 
> I'm doing a 3D simulation. Now I need something like variables in
> imperative languages. My mainLoop check for new events and renders
> scene. To use input for controling camera position I need variables. An
> equivalent code in C:
> 
>   void main_loop() {
>     int loop_num = 0;
>     bool run = 1;
>     SDLEvent e;
> 
>     while(run) {
>       while(SDL_PollEvent(&e)) {
>           if(e.type == SDL_KeyDown) {
>            if(... == SDLK_Left)
>                 camera_pos_x--;
>           } else if ...
>           ...
>       }
>     
>      drawScene();
>     
>       loop_num++;
>     }
>   }
> 
> How to implement camera_pos_x, y and z as variables, which chage values
> in run? This is only simplified example, but it's important to implement
> it in as most imperative form as possible.

Then you want IORef. 
http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data.IORef.html


Consider, however, that this kind of construct can be done without 
mutable variables. (warning, made-up code ahead)


main = loop 0 0 0 -- initial values
  where loop loop_num xpos ypos =
             do e <- pollEvent
                let xpos' = <calculate new xpos>
                    ypos' = <calculate new ypos>
                someActionInvolvingPosition xpos' ypos'
                when breakCondition (return ())
                loop (loop_num+1) xpos' ypos'




More information about the Haskell-Cafe mailing list