Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# function conciseness when generating random numbers

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)
like image 480
Lydon Ch Avatar asked Jun 01 '26 22:06

Lydon Ch


1 Answers

The difference is lifetime:

  • In the first, 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.
  • In the second, 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.

like image 149
ildjarn Avatar answered Jun 03 '26 17:06

ildjarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!