3 ms·
Hmm, as long as you do randomness in the IO monad, it's not any harder to do random numbers than it is to print to the screen. http://hackage.haskell.org/packa
by lurker17 15y ago
Hmm, as long as you do randomness in the IO monad, it's not any harder to do random numbers than it is to print to the screen.
http://hackage.haskell.org/packages/archive/random/1.0.0.2/doc/html/System-Random.html http://hackage.haskell.org/packages/archive/random/1.0.0.2/d...
getStdRandom :: (StdGen -> (a, StdGen)) -> IO aSource
Uses the supplied function to get a value from the
current global random generator, and updates the global
generator with the new generator returned by the
function. For example, rollDice gets a random integer
between 1 and 6:
rollDice :: IO Int
rollDice = getStdRandom (randomR (1,6))
Of course, printing to the screen can be a pain in the neck.
The cultural aversion to IO is Haskell's largest psychological problem. Newbies learn to avoid IO at all costs, and then never back off from the precipice and realize that sometimes IO is with the price you pay.
But yeah, it's harder to do IO in Haskell than non-pure languages, and you have to bend your brain to a different model.
In the worst case, though, you can just run your entire program in the IO monad, and then factor out your pure code bit by bit. None(?) of the Haskell tutorials will tell you do this, but it is the gentlest way to get real work done as a new-to-intermediate Haskeller.
- michaelochurch 15y agoThis is a fair point, but I'd generally prefer not to use the IO monad to generate random numbers because it feels "wrong", just like using IORef for mutable data when there are more "right" types feels wrong. Strictly speaking, pseudo-randomness isn't doing IO unless the source of randomness is considered something to which one is I/Oing.
- seabee 15y agoRight, but pseudo-randomness is still monadic because you are mutating the state of the random number generator. That it is in IO is an implementation detail of where that generator's state lives. It's been a little while since I worked with Haskell but I'll surprised if nobody ported e.g. Mersenne Twister to it, complete with its own Random monad. If not, maybe that could be a new project...
- jerf 15y agoYou have to get the randomness out of IO, because referential transparency and randomness of any kind (psuedo or otherwise) are fundamentally in opposition, but once you have the random source in hand, you can use it any way you like in otherwise pure code. The Random support in Haskell is set up to permit and to some extent support this usage, with the ability to "split" a random generator into something you use now and something you pass along. After that it's your responsibility to properly split & use, but I haven't yet found it to be a big problem in practice.