Haskell and random numbers -


i've been messing haskell few days , stumbled problem.

i need method returns random list of integers ( rand [[int]] ).

so, defined type: type rand = stdgen -> (a, stdgen). able produce rand io integer , rand [io integer] ( (returnr lst) :: stdgen -> ([io integer], stdgen) ) somehow. tips how produce rand [[int]]?

how avoid io depends on why it's being introduced in first place. while pseudo-random number generators inherently state-oriented, there's no reason io needs involved.

i'm going take guess , you're using newstdgen or getstdgen initial prng. if that's case, there's no way escape io. instead seed prng directly mkstdgen, keeping in mind same seed result in same "random" number sequence.

more likely, want prng inside io, pass argument pure function. entire thing still wrapped in io @ end, of course, intermediate computations won't need it. here's quick example give idea:

import system.random  type rand = stdgen -> (a, stdgen)  getprng =     rng <- newstdgen     let x = useprng rng     print x  useprng :: stdgen -> [[int]] useprng rng = let (x, rng') = randomints 5 rng                   (y, _) = randomints 10 rng'               in [x, y]  randomints :: int -> rand [int] randomints 0 rng = ([], rng) randomints n rng = let (x, rng') = next rng                        (xs, rng'') = randomints (n - 1) rng'                    in (x:xs, rng'') 

you might notice code using prng gets pretty ugly due passing current value , forth constantly. it's potentially error prone, since it'd easy accidentally reuse old value. mentioned above, using same prng value give same sequence of numbers, not want. both problems perfect example of makes sense use state monad--which getting off topic here, may want next.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -