Saturday, 15 January 2011

haskell - Understanding RandomGen#next -



haskell - Understanding RandomGen#next -

looking @ randomgen#next, docs say:

next :: g -> (int, g) next operation returns int uniformly distributed in range returned genrange (including both end points), , new generator.

playing in repl, would've expected x next have printed out same number.

ghci> allow x = getstdrandom ghci> x next 169285648 ghci> x next 473378030 ghci> x next 896978399

why isn't x next referentially transparent, i.e. calling x next returns same output?

look @ definition of getstdrandom:

getstdrandom :: (stdgen -> (a,stdgen)) -> io getstdrandom f = atomicmodifyioref thestdgen (swap . f)

in other words, (but atomically):

getstdrandom f = gen <- getstdgen allow (result, gen') = f gen setstdgen gen' homecoming result

so gets random number generator, runs function, puts new random number generator in place. when run getstdrandom next few times, it’ll retrieve random number generator @ start, thread random number generators such each next 1 receives new random number generator lastly one. means each invocation of next receives different random number generator.

but how can happen if getstdrandom next of type int? trick is, it’s not. it’s of type io int, ghci automatically execute , display result value of if int in first place.

if want random number generator environment , utilize several times, should 1 time (rather getting function threads rng state through function , returns io) , utilize that:

ghci> x <- getstdgen ghci> next x (803259519,803300211 40692) ghci> next x (803259519,803300211 40692) ghci> next x (803259519,803300211 40692)

haskell

No comments:

Post a Comment