Need help

D. Tweed tweed@compsci.bristol.ac.uk
Wed, 24 Jul 2002 10:44:51 +0100 (BST)


On 23 Jul 2002, Alastair Reid wrote:

> 
> > You shouldn't _need_ to be in the IO monad to get random numbers
> > (although if you choose to that can be a good choice). Clearly
> > there's the need to initialise the generator, but if you want
> > `random' random numbers (as opposed to a known sequence of random
> > numbers for debugging) getting the value of time via an
> > unsafePerformIO is as good as anything else. From then on, the
> > pseudo-random number generator will deterministically produce what
> > are hopefully `acceptably random looking' numbers.
> 
> Isn't this a very dangerous practice?  It's so very, very easy to
> break referential transparency when using unsafePerformIO with
> functions known to produce observably different results each time you
> call it.  And once you do this, all kinds of nice Haskell properties
> go to hell.

I would imagine it's an incredibly dangerous practice; I've only actually
done this for top level CAFs, and I'd imagine these are probably much less
likely to be duplicated by optimisation which is why it hasn't bitten me.
In general I do get the seed in a top level IO monad wrapper.

> Safer ways would be to use the monadic operators as intended to get
> random seeds and then use implicit parameters to pass them around
> (using a mild variation of John Hughes' approach to mutable
> variables).

That sounds a good way (implicit parameters are on my `learn about at
some point list'). All I was trying to say, in my rather confused email,
is that __one__ haskell idiom for dealing with random numbers is by
passing around StdGen's, in contrast with the C idiom of `calling a random
number generator function' and that if you pass in an initial StdGen you
don't need to be within the IO monad to do processing involving random
numbers.

It wasn't clear to me whether Vincenzo's e-mail was saying that you just
needed to be in IO to generate the seed or that you need to be in IO to do
anything that involves generating random numbers __after you've got the
seed__. Since I have to admit I really dislike having monads extend beyond
the top couple of levels of a program I wanted to point out that actually
generating and using random numbers can be done outside IO.

___cheers,_dave_________________________________________________________
www.cs.bris.ac.uk/~tweed/  |  `It's no good going home to practise
email:tweed@cs.bris.ac.uk  |   a Special Outdoor Song which Has To Be
work tel:(0117) 954-5250   |   Sung In The Snow' -- Winnie the Pooh