What is the workaround for OCaml: exception Invalid_argument("Random.int")?

1.4k Views Asked by At

I have this bit of code:

let rec random_list = function
  | 0 -> []
  | n -> ( Random.int max_int ) :: ( random_list (n-1) )

It compiles okay, but when I execute it, this error shows up:

exception Invalid_argument("Random.int")

What is the workaround for this issue ?

1

There are 1 best solutions below

5
On

The documentation says:

Random.int bound returns a random integer between 0 (inclusive) and bound (exclusive). bound must be greater than 0 and less than 2^30.

So the closest to what you want is:

let my_max_int = (1 lsl 30) - 1 in
Random.int my_max_int

As gsg suggested, using Random.bits () is cleaner to get almost the same result (it can also return 2^30 - 1).

If you really want to get any positive native integer, maybe you could use Random.nativeint, but this means you would have to use the module Nativeint and Nativeint.t instead of int.