Search code examples
smlsmlnj

Seeding SML/NJ's RNG on a Windows machine


How to seed SML/NJ's random number generator on a Windows machine?

The function Random.rand() takes a pair of integers and uses them to seed the random number generator. Based on my experience with other porgramming languages, I would expect there to be a relatively easy way to seed it based on the system clock (something like srand(time(null)); in C). Unless I am overlooking something obvious, there doesn't seem to be any straightforward way, at least if you are using Windows.

The closest I can find to time(null) in SML is Posix.ProcEnv.time, which returns Unix epoch time. Unfortunately, the Posix structures are not part of the Windows download, and the Windows structure (which is) doesn't seem to include any direct analogue of time.

The Timer structure does have ways of determining elapsed real time. I could write a function which does about half a second of meaningless calculation, time how long it takes, and figure out a way to extract a couple of integers from that. But: 1) this is an awful lot of work for something which is trivial in most languages, 2) more importantly -- it seems likely to result in the same seed being reused a non-trivial percentage of the times.

Another idea I had is that if I could access the Windows environment variable "TIME" I could use that. The following prints the time to the repl:

OS.Process.system "TIME/T";

but doesn't give any programatic access to the printed string.

OS.Process.getEnv "TIME";

sounds promising, but returns NONE.

If there really is no easy solution in SML/NJ -- are there options which work for some of the other implementations of SML such as Poly/ML?


Solution

  • The Basis Library's TIME signature has a function for returning the current time.

    val now: unit -> t