Stefan Ciprian Hotoleanu
Stefan Ciprian Hotoleanu

Reputation: 2292

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

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 ?

Upvotes: 4

Views: 1507

Answers (1)

Théo Winterhalter
Théo Winterhalter

Reputation: 5108

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.

Upvotes: 11

Related Questions