简体   繁体   中英

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)

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 eg initializing a collection of random numbers. However, unlike the first version, the second version has the advantage of being thread-safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM