Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 303
Stefan Ciprian Hotoleanu Avatar asked Dec 20 '22 03:12

Stefan Ciprian Hotoleanu


1 Answers

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.

like image 64
Théo Winterhalter Avatar answered May 01 '23 08:05

Théo Winterhalter