5

What's the best way to handle random number generation in Haskell (or what are the tradeoffs)?

I haven't really seen an authoritative answer.

Consider: minimizing the impact on otherwise pure functions, how / when to seed, performance, thread safety

zoo
  • 1,901
  • 1
  • 17
  • 25
  • The top-rated answer on this question: [http://stackoverflow.com/questions/2110535/sampling-sequences-of-random-numbers-in-haskell](http://stackoverflow.com/questions/2110535/sampling-sequences-of-random-numbers-in-haskell) gives an excellent write-up of how to thread a stateful random number generator through code. – stusmith Aug 19 '11 at 12:23

1 Answers1

3

IMHO, the best idea is to keep the generator in a strict state record. Then you can use the ordinary do-Syntax to work with the generator. Seeding is done only once - at the beginning of the main program (or at the beginning of each thread). You can avoid IO by using the split operation, which yields two random generators from one. (Different, of course).

As state is still pure, threadsafety can be guaranteed. Additionally, you can always escape state by giving a random generator to the function. This is useful for instance in case of automatic unit tests.

fuz
  • 88,405
  • 25
  • 200
  • 352
  • 1
    @zoo FYI there is a decent packaging of an RNG in the state monad already on hackage (in the MonadRandom and also CryptoMonadRandom packages). These just provide the generating in a state plus useful accessor functions to generate common types. – Thomas M. DuBuisson Aug 19 '11 at 17:54