I’ve been messing with Haskell few days and stumbled into a problem.
I need a method that returns a random list of integers ( Rand [[Int]] ).
So, I defined a type: type Rand a = StdGen -> (a, StdGen).
I was able to produce Rand IO Integer and Rand [IO Integer] ( (returnR lst) :: StdGen -> ([IO Integer], StdGen) ) somehow. Any tips how to produce Rand [[Int]]?
How to avoid the
IOdepends on why it’s being introduced in the first place. While pseudo-random number generators are inherently state-oriented, there’s no reasonIOneeds to be involved.I’m going to take a guess and say that you’re using
newStdGenorgetStdGento get your initial PRNG. If that’s the case, then there’s no way to completely escapeIO. You could instead seed the PRNG directly withmkStdGen, keeping in mind that the same seed will result in the same “random” number sequence.More likely, what you want to do is get a PRNG inside
IO, then pass that as an argument to a pure function. The entire thing will still be wrapped inIOat the end, of course, but the intermediate computations won’t need it. Here’s a quick example to give you the idea:You might notice that the code using the PRNG gets pretty ugly due to passing the current value back and forth constantly. It’s also potentially error prone, since it’d be easy to accidentally reuse an old value. As mentioned above, using the same PRNG value will give the same sequence of numbers, which is usually not what you want. Both problems are a perfect example of where it makes sense to use a
Statemonad–which is getting off topic here, but you may want to look into it next.