Is there a reason why one writes the line:
(fun max -> rndGen.Next(max))
https://github.com/sebfia/OffLog/blob/master/Shared/Helpers.fs#L8
let NextRandom =
let rndGen = new System.Random(int System.DateTime.Now.Ticks)
(fun max -> rndGen.Next(max))
Instead of just declaring the param max upfront and calling rndGen.Next(max), like this?
let NextRandom (max: int) =
let rndGen = new System.Random(int System.DateTime.Now.Ticks)
rndGen.Next(max)
The difference is lifetime:
rndGen is only seeded once and reused thereafter, and will live for the lifetime of the scope in which NextRandom is defined – if class-scope the lifetime of the class, or if module-scope the lifetime of the AppDomain.rndGen will be created – and seeded! – anew each time NextRandom is invoked.The net effect is that if NextRandom is invoked repeatedly in rapid succession, the second version can (and very likely will) return the same "random" number multiple times in a row, making it effectively useless for many normal usecases e.g. initializing a collection of random numbers. However, unlike the first version, the second version has the advantage of being thread-safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With