Merge branch 'clean_and_improve_numeric_examples' into 'master'
[why3.git] / stdlib / random.mlw
blob522d9e86cdc3412f56441c668c64e24fc307fefd
2 (** {1 Pseudo-random generators}
4    This easiest way to get random numbers (of random values of any type)
5    is to take advantage of the non-determinism of Hoare triples.
6    Simply declaring a function
8       [val random_int: unit -> {} int {}]
10    is typically enough. Two calls to [random_int] return values that can not
11    be proved equal, which is exactly what we need.
13    The following modules provide slightly more: pseudo-random generators
14    which are deterministic according to a state. The state is either
15    explicit (module [State]) or global (module [Random]). Functions [init] allow
16    to reset the generators according to a given seed.
18  *)
20 (** {2 Mutable states of pseudo-random generators}
22   Basically a reference containing a pure generator. *)
24 module State
26   use int.Int
28   type state = private mutable { }
30   val create (seed: int) : state
32   val init (s: state) (seed: int) : unit writes {s}
34   val self_init (s: state) : unit writes {s}
36   val random_bool (s: state) : bool writes {s}
38   val random_int (s: state) (n: int) : int writes {s}
39     requires { 0 < n }
40     ensures  { 0 <= result < n }
42 end
44 (** {2 A global pseudo-random generator} *)
46 module Random
48   use int.Int
49   use State
51   val s: state
53   let init (seed: int) = init s seed
55   let self_init () = self_init s
57   let random_bool ()
58   = random_bool s
60   let random_int (n: int)
61     requires { 0 < n }
62     ensures  { 0 <= result < n }
63   = random_int s n
65 end