I was wondering if there was a way to use a randomly generated number (using randomRIO from System.Random per example) as a list index operator in Haskell?
Now I know that the type of randomRIO is (a,a) -> IO a and (!!) needs an Int so you can't do it the regular way. I also know that all functions that return something of the form IO are the "impure" part of Haskell and shouldn't be used in its "pure" part. Now (I think) I could maybe use a function from System.IO.Unsafe to get the job done, but I have been told that using functions from that particular library is equal to committing a mortal sin so I won't.
The reason I need to perform this operation is because I am refining a Pacman game I wrote earlier this year. Without going into too much detail about the inner workings of Pacman; when Pacman eats an Energizer, all the Ghosts go into Frightened mode where they (pseudo)randomly decide which way to go at every intersection of the playable maze. I have wrote my game in such a way that the maze is divided like a grid and when a Ghost in Frightened mode gets to an intersection it analyses all the surrounding fields to determine the possible direction. This analysis is a function that takes the position of the ghost and returns a list of possible positions to go to.
Now I think it is possible to write a function that does this by using a do-block to "protect" the outside from the impure actions performed in the do-block, but I tried for a couple of hours and I couldn't figure it out.
So my question: is using a randomly generated number as a list index operator possible or should I seek out other ways of fixing my problem?
Thanks for reading if you made it this far :)
Aucun commentaire:
Enregistrer un commentaire