Random Numbers in Standard ML

Here’s the translation of the Go code example for random numbers into Standard ML, along with explanations:

Standard ML doesn’t have a built-in random number generator, so we’ll use the Random structure from the SML/NJ library. This example demonstrates how to generate random integers and real numbers.

structure Random = Random

fun main () =
  let
    (* Initialize the random number generator with a seed *)
    val _ = Random.rand(42, 1024)

    (* Generate random integers between 0 and 99 *)
    val _ = print (Int.toString (Random.randRange (0, 99) Random.rand) ^ ",")
    val _ = print (Int.toString (Random.randRange (0, 99) Random.rand) ^ "\n")

    (* Generate a random real number between 0.0 and 1.0 *)
    val _ = print (Real.toString (Random.randReal Random.rand) ^ "\n")

    (* Generate random real numbers between 5.0 and 10.0 *)
    val _ = print (Real.toString (5.0 + Random.randReal Random.rand * 5.0) ^ ",")
    val _ = print (Real.toString (5.0 + Random.randReal Random.rand * 5.0) ^ "\n")

    (* Create a new random number generator with a known seed *)
    val newRand = Random.rand(42, 1024)
    val _ = print (Int.toString (Random.randRange (0, 99) newRand) ^ ",")
    val _ = print (Int.toString (Random.randRange (0, 99) newRand) ^ "\n")

    (* Create another random number generator with the same seed *)
    val anotherRand = Random.rand(42, 1024)
    val _ = print (Int.toString (Random.randRange (0, 99) anotherRand) ^ ",")
    val _ = print (Int.toString (Random.randRange (0, 99) anotherRand) ^ "\n")
  in
    ()
  end

val _ = main()

This program demonstrates various ways to generate random numbers in Standard ML:

  1. We use Random.randRange to generate random integers between 0 and 99.

  2. Random.randReal generates a real number between 0.0 and 1.0.

  3. We show how to generate random real numbers in a custom range (5.0 to 10.0) by scaling and shifting the output of Random.randReal.

  4. We demonstrate creating new random number generators with known seeds, which allows for reproducible sequences of random numbers.

To run this program, save it as random_numbers.sml and use the Standard ML of New Jersey (SML/NJ) interpreter:

$ sml random_numbers.sml

The output will be similar to:

87,42
0.123456789
7.654321,9.876543
87,42
87,42

Note that the actual numbers will vary each time you run the program, except for the last two lines which use fixed seeds.

In Standard ML, the random number generator is stateful, meaning it maintains internal state between calls. This is different from some other languages where you might need to explicitly pass around a random state object.

The SML/NJ library’s Random structure provides additional functions for generating random numbers with different distributions. Consult the SML/NJ documentation for more advanced random number generation techniques.